Linux руководство iptables

Время на прочтение
6 мин

Количество просмотров 16K

 Схема работы Iptables:

Схема работы Iptables:

Iptables как с ним работать 

Iptables — это мощный инструмент управления сетью в Linux, который позволяет администраторам управлять входящими и исходящими пакетами данных. Это основной инструмент для настройки межсетевых экранов в системах Linux.

Введение в Iptables

Iptables работает путем проверки пакетов данных на соответствие определенным критериям и выполнения заданных действий, если пакеты соответствуют этим критериям. Эти критерии и действия определяются в таблицах, которые состоят из набора правил.

В Iptables есть четыре основные таблицы:

  1. Filter — это основная таблица, используемая для фильтрации пакетов.

  2. NAT — эта таблица используется для настройки NAT (Network Address Translation).

  3. Mangle — эта таблица используется для специальной обработки пакетов.

  4. Raw — эта таблица используется для обхода системы отслеживания состояний.

Каждая таблица состоит из набора цепочек. Цепочки — это последовательности правил, которые применяются к пакетам. В Iptables есть три встроенные цепочки:

  1. INPUT — эта цепочка применяется к пакетам, которые предназначены для самой системы.

  2. FORWARD — эта цепочка применяется к пакетам, которые проходят через систему.

  3. OUTPUT — эта цепочка применяется к пакетам, которые исходят из системы.

Базовые команды Iptables

Просмотр текущих правил

Чтобы просмотреть текущие правила, используйте команду iptables -L. Это покажет все правила в таблице filter. Чтобы просмотреть правила в другой таблице, используйте флаг -t, например, iptables -t nat -L.

Добавление новых правил

Чтобы добавить новое правило, используйте команду iptables -A. Например, чтобы заблокировать весь входящий трафик от IP-адреса 192.168.0.100, вы можете использовать следующую команду:

iptables -A INPUT -s 192.168.0.100 -j DROP 

В этой команде -A INPUT добавляет новое правило в цепочку INPUT, -s 192.168.0.100 определяет исходный IP-адрес, а -j DROP указывает, что все пакеты, соответствующие этому правилу, должны быть отброшены.

Удаление правил

Чтобы удалить правило, вам нужно знать его номер в цепочке. Вы можете узнать номера правил, используя команду iptables -L --line-numbers. Затем вы можете удалить правило, используя команду iptables -D и номер правила. Например, чтобы удалить первое правило в цепочке INPUT, вы можете использовать следующую команду:

iptables -D INPUT 1 

Изменение дефолтного политики

Вы можете изменить дефолтную политику для цепочки, используя команду iptables -P. Например, чтобы отклонить все входящие пакеты по умолчанию, вы можете использовать следующую команду:

iptables -P INPUT DROP 

Сохранение и восстановление правил

По умолчанию, правила iptables не сохраняются после перезагрузки системы. Чтобы сохранить текущие правила, вы можете использовать команду iptables-save. Это выведет текущие правила в формате, который можно использовать для восстановления с помощью команды iptables-restore.

iptables-save > /path/to/iptables/rules 

Затем, чтобы восстановить правила, вы можете использовать следующую команду:

iptables-restore < /path/to/iptables/rules 

Примеры использования Iptables

Блокировка IP-адреса

Чтобы заблокировать весь трафик от определенного IP-адреса, вы можете использовать следующую команду:

iptables -A INPUT -s 192.168.0.100 -j DROP 

Открытие порта для входящего трафика

Чтобы открыть порт для входящего трафика, вы можете использовать следующую команду:

iptables -A INPUT -p tcp --dport 80 -j ACCEPT 

В этой команде -p tcp указывает на протокол (в данном случае TCP), --dport 80 указывает на порт (в данном случае 80), а -j ACCEPT указывает, что все пакеты, соответствующие этому правилу, должны быть приняты.

Настройка простого межсетевого экрана

Вы можете использовать iptables для настройки простого межсетевого экрана. Например, вы можете разрешить весь исходящий трафик, разрешить входящий трафик только на определенные порты и отклонить все остальные входящие пакеты.

iptables -A OUTPUT -j ACCEPT iptables -A INPUT -p tcp --dport 22 -j ACCEPT iptables -A INPUT -p tcp --dport 80 -j ACCEPT iptables -A INPUT -p tcp --dport 443 -j ACCEPT iptables -P INPUT DROP 

В этом примере разрешен весь исходящий трафик, а входящий трафик разрешен только на порты 22 (SSH), 80 (HTTP) и 443 (HTTPS). Все остальные входящие пакеты отклоняются.

Расширенное использование Iptables

Логирование

Iptables предоставляет возможность логирования пакетов, что может быть полезно для отладки и мониторинга. Для включения логирования используйте цель LOG. Например, чтобы залогировать все отброшенные пакеты, можно использовать следующую команду:

iptables -A INPUT -j LOG --log-prefix "Dropped Packet: " iptables -A INPUT -j DROP 

Здесь --log-prefix "Dropped Packet: " добавляет указанный префикс к каждому лог-сообщению, что упрощает фильтрацию и анализ логов.

Создание пользовательских цепочек

Iptables позволяет создавать пользовательские цепочки для более гибкого управления правилами. Например, вы можете создать цепочку для обработки всего трафика от определенного IP-адреса:

iptables -N MY_CHAIN iptables -A MY_CHAIN -s 192.168.0.100 -j DROP iptables -A INPUT -j MY_CHAIN 

В этом примере команда -N MY_CHAIN создает новую цепочку с именем MY_CHAIN. Затем добавляется правило, которое отбрасывает все пакеты от 192.168.0.100. Наконец, цепочка MY_CHAIN добавляется в цепочку INPUT, что означает, что все входящие пакеты будут также проходить через цепочку MY_CHAIN.

Использование состояний пакетов

Iptables может отслеживать состояние пакетов, что позволяет создавать более сложные правила. Например, вы можете разрешить только входящие пакеты, которые являются частью уже установленного соединения:

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT 

В этом примере -m state указывает на использование модуля состояний, а --state ESTABLISHED,RELATED указывает, что правило применяется только к пакетам, которые являются частью уже установленного или связанного соединения.

Использование Iptables для создания VPN

Iptables также может быть использован для создания VPN (Virtual Private Network). Это может быть полезно для создания безопасного соединения между удаленными системами. Например, вы можете использовать iptables для настройки IPsec VPN, используя модуль «policy» для определения правил обработки трафика.

iptables -A INPUT -m policy --dir in --pol ipsec -j ACCEPT iptables -A OUTPUT -m policy --dir out --pol ipsec -j ACCEPT 

В этом примере -m policy указывает на использование модуля «policy», --dir in и --dir out указывают на направление трафика, а --pol ipsec указывает на использование IPsec политики.

Использование Iptables для ограничения скорости

Iptables также может быть использован для ограничения скорости сетевого трафика, что может быть полезно для управления пропускной способностью. Для этого можно использовать модуль «limit». Например, вы можете ограничить количество новых SSH-соединений до 3 в минуту следующим образом:

iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m limit --limit 3/min -j ACCEPT 

В этом примере -m limit --limit 3/min указывает на ограничение скорости, а остальная часть команды определяет, что она применяется к новым SSH-соединениям.

Использование Iptables для редиректа трафика

Iptables может быть использован для редиректа трафика, что может быть полезно для перенаправления трафика на другой порт или сервер. Например, вы можете перенаправить весь входящий трафик на порт 80 на порт 8080 следующим образом:

iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080 

В этом примере -t nat указывает на использование таблицы NAT, -A PREROUTING добавляет правило в цепочку PREROUTING, --dport 80 указывает на исходный порт, а --to-port 8080 указывает на порт назначения.

Iptables — это мощный и гибкий инструмент, который может быть использован для решения множества задач управления сетью. Однако, как и любой мощный инструмент, он требует тщательного понимания и практики для эффективного использования.

Заключение

Iptables является мощным и гибким инструментом для управления сетью в Linux. Он предлагает широкий спектр функций, включая фильтрацию пакетов, NAT, логирование и многое другое. Однако, несмотря на его мощь, iptables может быть сложным для новичков. Надеюсь, эта статья помогла вам разобраться в основах работы с iptables и дала вам основу для дальнейшего изучения этого мощного инструмента.

�����blueflux@koffein.net
������Copyright (C) 2001-2003 Oskar Andreasson
����

�������: ������ �������

������� �������� � ���� tar.gz ������

��������� ������ ��������� ����� �������� �� ������: http://iptables-tutorial.frozentux.net
.

����������� ����������� �/��� ����������� �������
��������� ��� ��� �����, � ������������ � ������������,
��������� � GNU Free Documentation License, ������ 1.1.
������������� ��������� �������� ������ «��������»
� ��� ���������� ����� �������, � ��� �� �������,
������������ ������� «Original Author: Oskar
Andreasson», ����� GNU Free Documentation License
�������� � ������ �������� � ��������� � ������ «GNU
Free Documentation License».

��� �������� � ������ ����������� ��������� ��� ��������
GNU General Public License. ��� �������� ��������
����������������� � ����� ������������ �/��� ����������������
� ������������ � ��������� GNU General Public License ������
2.

�������� ���������������� � ������� �� ��, ��� ��� �����
������� ���, �� ��� ����� ���� ��������. �� ��������������
����������� ����������� � ������ GNU General Public
License.

� ������ ���������� ������ ���������������� ����� GNU
General Public License, � ������ «GNU General Public
License»; � ������ �� ���������� �� ������ �������� ��
������ Free Software Foundation, Inc., 59 Temple Place, Suite
330, Boston, MA 02111-1307 USA



����������

������ �����, � ����� �� ��������� ������ �������� ����
������������� ������� ������ (Ninel). ��� ������������ ����
������, ��� � �����-���� ����� ���������� ��.

��-������ — ���� ������������� Linux ��������� ���
������������� ������������ �������, �� �� ����������
����������� ����.


�� ������

� �������, ������� ����� �� ����� ��������� ���������� �����
���������� �����������, ������������ ���� � ��������� ���� �
������� � ��������, � �������������� �� ������������. � � ����
��������� ������� �� ipchains � iptables �������� �����������.
����� ��� ��������� ������������ ����� ����, �� ����� ��������
��� ������, �������� ������������ �����, ������ ��� ���������
�������� � ��������� FTP (passive FTP) ��� ��������� DCCIRC (outgoing DCC in IRC), ��� �������
����� �� ������� ����������� ����������� � ����� ����������
������� ��� ���������� ����������. � ����� ������ � ����������
� ���������� ‘���������’, ��������������� �� ipchains,
� ������ ��� iptables �� ������ ������� � ��������������
�������. ������� �� � ��� �� ��������������� ����, ���
���������� � ����� ������ ipchains � ipfwadm
‘���������’ �� iptables!


��� ������ ���� ��������

���� �������� �������, ��� ����� ��������� ���������
��������� �������������� ���� iptables. ����� �� �� �������
���������� �� ������� � iptables ��� � netfilter. ���� ��
����������� � ����, �� ������ ��������� � ��������
�������������, � ��� � ����� ����� �������� ���, �������������
�� ���������� ����� ������. �� ����������� ���� iptables �
netfilter ����������� �� �������� ������, ���� ������� ���� —
��� «������������». ���������� � ����� �������
����������� ���������� �� ������� �������� ������� Netfilter.

������������� ����� ��������, ��� ��� ��������� �������
������, ����������� � ������� �����������, �� �����������
��������� ������� �����-���� ������ ������ netfilter. ��������
���� �������� — �������� ������� ��������� ������ ������ �
��������, � �������� �� ������ �����������. ��������, � ����
��������� �� ����������, ��� ������� ���������� Apache 1.2.12
�� HTTP ����� (���������� � �������� �� �������, ��� �������
���� ����, �� �� ������ �������).

���� �������� ��� ������� � ����� ���� ���������� �������,
������� � � �� �� ����� ���������� ������ ������� �� iptables.
�� �� �������� ���������� �� ��������� � ��������� ��
patch-o-matic �� ��� ������� �������, ��� ������������� ��
������� ����� ������, ����� ��������� ���� ������ ���������.
���� � ��� ��������� ������������� � ��������� ���������� ��
������������ patch-o-matic, �� ��� ������� ���������� �
������������, ������� ������������ ���������� patch-o-matic,
��� �������� �� ������� �������� ������� Netfilter.


��������������� �������

������ ����������� ������������ ������� � �������� ���������
�������� � Linux/Unix, ����� ��������� ��������� ��������.
����� ����, �� ������ ����� — ��� ����������� ���� ������������
������� � ����� ��������� ������������� � ��� ����������
����������.

� ����������, ��������� ��� ��������, ������� ��������
��������� ��� ��������� ��� ����� ����� �������� �����
���������, ������ � �� ��������, � ������� �� ��� ���-����
����������� ������� ��������� ��������.


������������ ����������

� ������ ��������� ������� ��������� ���������� �� ���������
���������� ���������� ����:

  • �������, �������� �������������, � �����, ���������� �
    ���������� ������ ������, ������������ ������������
    �������, ����� ����, ���� ������������ ������������ ������
    �������:

    [blueflux@work1 neigh]$ ls
    default  eth0  lo
    [blueflux@work1 neigh]$
        
    
  • ��� ������� � ����� �������� ������������ ������ ������� .

  • ��� ���������� �� ���������� �����������, � ��� �� �
    ���������� ���������� ���� ��� ����������� �������� �������
    (��������: �������� (loopback) ���������), ������������ ��������.

  • ����� ������ � ���� � ������ ������������ ����� �������:
    /usr/local/bin/iptables.


����� 1. ��������

1.1. ������ ���� �������� ������
�����������

������ ���, � ��������, ��� ���������� �������� ������ �
HOWTO �� ����� ���������� �� iptables � �������� ��������
������� (netfilter), ������������� � ����� ����� ���� 2.4.x
Linux. ����� ����� �������, � ��������� �������� �� ���������
������� �� ������ ����� ������������, �������� ��������
��������� ������� (state matching). ����������� �� ���
����������������� � ����� ������� rc.firewall.txt, �������
�� ������ �������� � /etc/rc.d/. ��� ���, ���� ���������,
����� ��������, ��� ���� ���� ������������� ��� ������� ��
masquerading HOWTO.

��� �� �� ������� ��������� �������� rc.flush-iptables.txt,
���������� ����, ������� �� ������ ������������, ��� �����
����, ��� ������������� �������� ��� ���� ������������.


1.2. ��� �� ��� �������

� ���������������� � ������ ������� (Marc Boucher) �
������� ������� ������� ������������� netfilter. ���������
�������, ������� �������� ��������������� �� �� ������ �
�������� ������� �����������, ������� ���������� ����
�������� ��� boingworld.com, � ������ �������� �� ����
������������ ����� frozentux.net. � ������� ����� ���������
�� �������� ������� ��������� ��� �� ����� �, �������, ��� �
����� �������� ��� �� ������ ����� � ������ iptables
����������� ������. ������� ����� ��������� ���������� ��
����� rc.firewall.txt, ��� ��� � ������, ��� ������������
������� — ������ ������ �������� iptables. � ������ ��
�������� �������� ������ � ������� �� ����������. ���
��������� ��������� ��������, ���� ��������� ����������
��������. �, ������ ���, ����� � ��� ��������� �����������,
�� ������ ���������� � ����� �����������.


1.3. �������, ������������ � ������
���������

���� �������� �������� ��������� ��������, ������� �������
�������� ������, ��� �� ����������� � ����.

DNAT — �� ����. Destination Network Address Translation —
��������� �������� ������ ����������. DNAT — ��� ���������
������ ���������� � ��������� ������. �������� ������������ �
���� � SNAT. �������� ���������� — �������������
������������� ��������� IP-������ ����������� ������������
��� ������ � �������� � �������������� �������������� �������
����� ������� ��������.

«�����» (Stream) — ��� ���� ��������
��������������� ����������, ����� ������� ���������� �
����������� ������. � ����������� ���� ������ ��� �����������
����������, ����� ������� ���������� �� ������� ���� 2 ������
� ����� ������������. � ������ TCP ��� ����� ��������
����������, ����� ������� ���������� SYN ����� � �����
����������� SYN/ACK �����. �� ��� ��� �� ����� �������������
� �������� SYN ������ � ����� ��������� ICMP Host
unreachable. ������� �������, � ��������� ���� ������ �
���������� ������� ��������� ����������.

SNAT — �� ����. Source Network Address Translation —
��������� �������� ������ �����������. SNAT — ��� ���������
��������� ������ � ��������� ������. �������� ���������� —
������������� ������������� ��������� IP-������ �����������
������������ ��� ������ � ��������. � �������� ����� ��������
�������� IP-�������, �� ��������� IPv4, ������������ �����, �
��� �� ������� �� ���� (������� �� IPv6 �������� ���
��������).

«���������» (State) — ��� ���� ��������
��������������� ���������, � ������� ��������� �����,
�������� RFC 793 — RFC 793 — Transmission Control
Protocol
, � ����� ����������, ������������ �
netfilter/iptables. ���� �������� ���� �������� �� ��� ����,
��� ����������� ��������� �������, ��� ��� ���������� ��� �
��� ������� ���������, ������������ Netfilter, �� ���������
������������� ���������� ���� RFC 793.

«������������ ������������» (User space) — ���
���� �������� � ������������ ���, ��� ����������� ��
��������� ����, ��������: ������� iptables -h ����������� ��
��������� ����, � �� ����� ��� ������� iptables -A FORWARD -p tcp -j
ACCEPT
����������� (��������) � ������������ ����,
��������� ��� ��������� ����� ������� � ����������
������.

«������������ ����» (Kernel space) — � �������
��� ������� ������� �������� ������������, �������� �������
«������������ ������������». ������������� �����
���������� — � �������� ����.

«Userland» — ��. «������������
������������».


����� 2. ����������

����� ������ ����� �������� �������� ������ � ��������� ���
����, ������� netfilter � iptables ������ � Linux �������. ���
�� ��� ������ ������ ��� ���������� � ��������� ����������
����� (firewall).


2.1. ��� ����� iptables

������ iptables ����� ���� ��������� �
�������� �������� ������� Netfilter. ����� ����, ��� ������
iptables ��������������� ������� ������ ���� ����������������
���� ����� Linux-�������. ��������� ���� ����� �����������
����.


2.2. ��������� ����

��� ����������� ������� ������������ iptables, � ������� ������� make config ��� �� ��������
(make menuconfig ��� make xconfig ����. �����.), � ����
������ ���� �������� ��������� �����:

CONFIG_PACKET — ��� �����
���������� ��� ����������, ���������� ��������������� �
�������� ������������, ��������: tcpdump ��� snort.

Note

������ ������, ����� CONFIG_PACKET �� ������������
������ iptables, ��, ��������� ��� ������������
�������� �����, � ������� �� � ������. ���� ��� ���
����� �� �����, �� ������ �� �� ��������.

CONFIG_NETFILTER — ��� �����
����������, ���� �� ����������� ������������ ��������� �
�������� �������� ������ (firewall) ��� ����� (gateway) �
��������. ������� �������, ��� ��� ����������� �����������,
����� ����� ����� ������ ��� �����������!

� ������� ����� �������� �������� ��� ����� ���������,
�.�. ��� ����� Ethernet, PPPSLIP. ��� ����� ���������� ���
����������� ������� ������������ iptables, ��� ���������
�������������� ������������ �������� �������� � ����
��������� �������������� �����. ���� ���������� ������ �����
��� ���� 2.4.9 � �� ������� ��������:

CONFIG_IP_NF_CONNTRACK —
����������� ����������. ����������� ����������, ����� �����
�������, ������������ ��� ���������� ������� ������� �
������������ (NATMasquerading). ���� �� �����������
������� ������� ����� (firewall) ��� ��������� ����, �� ���
����������� ����������� ��� �����. � �������, ���� ������
��������� ��� ������ rc.firewall.txt.

CONFIG_IP_NF_FTP — �����������
FTP ����������. ����� �� FTP ���� ������� ����������, �����
������������ ������� ������ �����������. ���� �� ��������
���� ������, �� �� ����������� � ����������� ��� ��������
��������� FTP ����� ������� ����� (firewall).

CONFIG_IP_NF_IPTABLES — ���
����� ���������� ��� ���������� �������� ����������,
�������������� ������� ������� (NAT) � ������������
(masquerading). ��� ��� �� ������ ������ �� ������� ������ �
iptables.

CONFIG_IP_NF_MATCH_LIMIT — ����
������ ������������, ������ �� ������������ � �������� rc.firewall.txt. ��
������������� ����������� ����������� ���������� �������� ���
���������� �������. ��������, -m limit —limit 3/minute
���������, ��� �������� ������� ����� ���������� �� ����� 3-�
������� � ������. ����� �������, ������ ������ �����
�������������� ��� ������ �� ��������� ���� «����� �
������������».

CONFIG_IP_NF_MATCH_MAC — ����
������ �������� ������� �������, ���������� �� MAC-���������. ��� ��������, ������
������� ����� ����� ���� ����������� ����������
Ethernet-�����, ����� �������, ���������� �����������
����������� ������, ����������� � ������������ MAC-������� (�.�. � ������������
������� ����). �������, ������, �������� ��� ������ ������ ��
������������ � rc.firewall.txt ��� ���
���� ��� � ������ �����������.

CONFIG_IP_NF_MATCH_MARK —
������� ���������� ������� MARK. ��������, ��� �������������
������� MARK �� �������� �����������
�������� ��������� ������, � �����, � ������ ��������, �
����������� �� �������� �����, ��������� ������� �
������������� ����������� ������. ����� ��������� ��������
������� MARK ���������� ���� � ������
���������.

CONFIG_IP_NF_MATCH_MULTIPORT —
���� ������ �������� ������� ������� � ��������� ��
�������������� ������ � ��������� ������� ������
���������/���������.

CONFIG_IP_NF_MATCH_TOS — ����
������ �������� ������� �������, ������������ �� ���������
���� TOS � ������. ���� TOS ��������������� ��� Type Of
Service. ��� �� ���������� ��������� ������������� �
���������� ���� ����� ���� � ����������� �������� � �������
mangle ��� ��������� ip/tc.

CONFIG_IP_NF_MATCH_TCPMSS — ���
����� ��������� ����������� �������� ���� MSSTCP-�������.

CONFIG_IP_NF_MATCH_STATE — ���
���� �� ����� ��������� ������������������ �� ��������� �
ipchains. ���� ������ �������������
����������� ���������� TCP ��������, ����������� �� ��
��������� (state). � �������, ��������, ��� �� �����
������������� TCP ����������, � ��������� � ��� �����, �����
����� ���������� �� ������ ���������� ����� ��������� ESTABLISHED (�������������
���������� — ����. ���). ��� ����������� ������ ������������
� ������� rc.firewall.txt.

CONFIG_IP_NF_MATCH_UNCLEAN —
���� ������ ��������� ����������� �������������� �������� IP, TCP, UDPICMP ������� �� ������� ������� � ���
��������������, «�����������», ������. ���������
��� ��, � �������, ������� ����������� «��������»
��������� ���� ������. ������ ������� ��������, ��� ������
������ ���� ��������� �� ����������������� ������ � �� ��
���� ������� ����� �������� ���������, ������� ������� ������
����� ���� ���������, ��� �� �� «��������» ������
���������� ������.

CONFIG_IP_NF_MATCH_OWNER —
�������� «���������» ���������� (socket). ���
�������, �� ����� ��������� ������ ������������ root ��������
� Internet. ���� ������ ��� ������� ��� ������ ������ �
iptables. ������� ��������, ���
������ ������ ����� ������ ������������������ � ����� ��
������ ��������� ���� �������.

CONFIG_IP_NF_FILTER — ����������
������� filter � ������� � �������� �
�������������� ����������. � ������ ������� ��������� �������
INPUT, FORWARDOUTPUT. ���� ������ ����������, ����
�� ���������� ������������ ���������� �������.

CONFIG_IP_NF_TARGET_REJECT —
����������� �������� REJECT, ������� ���������� ��������
ICMP-��������� �� ������ � ����� ��
�������� �����, ������� ����������� �������� ��������.
���������, ��� TCP ����������, � ������� �� UDPICMP, ������ ����������� ���
����������� ������� TCP RST.

CONFIG_IP_NF_TARGET_MIRROR —
����������� �������� ����������� ������ ������� (���������).
��������, ���� ��������� �������� MIRROR ��� �������, ������ � ���� HTTP ����� ���� ������� INPUT (�.�. �� ��� WEB-������ ����.
�����.), �� ����� ����� ��������� ������� (�������) �, �
����������, ����������� ������ ���� ����������� ��������
���������. (��� ���� �������� «����»: ���� �
����������� ����� WEB-������, ���� �� �������� �� ��� ��
�����, ���� � ����������� ���� �������� ���������, � �.�. .
����-�� ���������� �������� � ����, ��� � ����� ������
����������� ��� �������� ���, ��� ����� �� ����� �� ��������
�� ���� ����������� ������, � ����� ������, �������� MIRROR ������ ������� �����
����������� � ���������� � ������ ���������� ����� � ����
����. �����.)

CONFIG_IP_NF_NAT — ����������
������� ������� � ��������� �� �����. � ������� ���� ����� ��
������� ���� ����� � �������� ���� ����������� �����
��������� ����, ���� ���� ���� ���������� IP-�����. ��� �����
���������� ��� ������ ������� rc.firewall.txt.

CONFIG_IP_NF_TARGET_MASQUERADE —
�����������. � ������� �� NAT, ����������� ������������ � ���
�������, ����� ������� ���������� ��� IP-����� � ���������,
�.�. ��� ������� DHCP, PPP, SLIP ��� ������-���� ������� �������
�����������, ���������������� ������������ ���������
IP-������. ����������� ���� ��������� ����� ������� ��������
�� ���������, �� ��������� � NAT, ������ �� �������� �
���������, ����� ���������� ������� ������� �����������
������� IP-�����.

CONFIG_IP_NF_TARGET_REDIRECT —
���������������. ������ ��� �������� ������������ ��������� �
��������������. ������ ����, �����
������ ���������� ����� ������, ��� �������� ��������������
����� �� ������ ���� �������� ������ (������-������� ����.
�����.). ������� �������, ����� �������� �� ����� ���������
«����������
�������������»
.

CONFIG_IP_NF_TARGET_LOG —
��������� �������� LOGiptables. �� ����� ������������
���� ������ ��� �������� ��������� ������� � ���������
������� (syslog). ��� ����������� ����� ��������� ������
�������� ��� ������� ����� ���������.

CONFIG_IP_NF_TARGET_TCPMSS — ���
����� ����� �������������� ��� ����������� �����������,
������������� ���������� ������������ (Internet Service
Providers), ������� ��������� ICMP Fragmentation Needed ������. �
���������� ����� ����������� ������� ����������� ����� ��
���������� web-��������, ssh ����� ��������, � �� ����� ���
scp ���������� ����� ������������ ���������� � ��. ���
����������� ��������� ���� ����������� �� ����� ������������
�������� TCPMSS ����������� �������� MSS (Maximum Segment Size) (������ MSS
�������������� �������� MTU ���������� ���������� ����� 40
���� ����. �����.). ����� ������� �� �������� �����������
���������� ��, ��� ������ netfilter �������� «����������
������������� ����������� ��� ��������»
(«criminally braindead ISPs or servers») � �������
�� ������������ ����.

CONFIG_IP_NF_COMPAT_IPCHAINS —
��������� ������������� � ����� ������ ����������� ipchains. ������ ��������, ���
��������� ���� ������������� ����� ��������� � � ����� �����
2.6.x.

CONFIG_IP_NF_COMPAT_IPFWADM —
��������� ������������� � ipfwadm, �� ������ �� �� ��� ���
����� ������ �������� ���������� ������������.

��� �� ������ ������, � ��� ������� �������������� �������
������. ������ ����� �������� � ���� ������ 2.4.9. ���� ���
����������� �������������� ����������� — ������� ��������
�������� �� ���������� patch-o-matic, ������� ���������
���������� ������� ���������� �������������� ������� � Netfilter. Patch-o-matic — ��� ����� ����������,
�������, ��� ��������������, � ������� ����� �������� �
������ ����.

��� ������ �������� rc.firewall.txt ���
���������� ����� �������� � ���� ��������� ����� ��� �������
��������������� ������������ ������. �� ����������� ��
������, ����������� ��� ������ ������ ���������, �����������
� ���������� � ��������� ���� ���������.

  • CONFIG_PACKET

  • CONFIG_NETFILTER

  • CONFIG_IP_NF_CONNTRACK

  • CONFIG_IP_NF_FTP

  • CONFIG_IP_NF_IRC

  • CONFIG_IP_NF_IPTABLES

  • CONFIG_IP_NF_FILTER

  • CONFIG_IP_NF_NAT

  • CONFIG_IP_NF_MATCH_STATE

  • CONFIG_IP_NF_TARGET_LOG

  • CONFIG_IP_NF_MATCH_LIMIT

  • CONFIG_IP_NF_TARGET_MASQUERADE

���� �������� ������ ���������� ����������� ����� ���� ���
�������� rc.firewall.txt ��������
�����, ����������� ��� ������ �������� ��������� �� �������
����� � ��������������� �������� ����. ������ �� ��
����������� �� ������� �������� � ������ ��� ��������.


2.3. ��������� ������

� ������ ������� ��������� ��� ������� (��������������)
����� iptables. ������ ������ �
������������ ������� ������� �� ������������ ���� � �� ������
��� ��������. ��������� ������������ ������������
������������� ������ iptables, ���� �� ��� — Red Hat.
������, � RedHat ���� ����� �� ��������� ��������, �������
���� �� ���������� ��� ��� �������� � ������ � � ������
�������������.


2.3.1. ������ ������

��� ������ ����� � ��������� �������� iptables ����� �����������. ��
����� ������������� ����� iptables 1.2.6a � ���� ����� 2.4.
��������� ��� ������, �������� bzip2 -cd iptables-1.2.6a.tar.bz2 | tar
-xvf —
(���������� ����� ��������� ����� ��������
tar -xjvf
iptables-1.2.6a.tar.bz2
). ���� ���������� ������
������, �� ����� ����� �������� � �������� iptables-1.2.6a. ��
�������������� ����������� �� ������ ���������� � ����� iptables-1.2.6a/INSTALL, �������
�������� ��������� ���������� �� ������ � ���������
������.

����� ���������� ��������� ��������� � ����
�������������� ������� � �����. ����, ����������� �����,
����� �������� ������ ��������� «������»
(patches) �� ����. �� ���� ���� �� ��������� ����������,
�������, ��� ���������, ����� �������� � ���� �
�������.

Note

��������� �� ��� ��������� ���� ��
����������������� ������ � ��������� ���� ������
����� ��������� �� ������ �����������, ������ �����
��� ���� ����������� ���������� ������� �
��������.

�������� ���� ���, ������ ������� (�����������,
������� ������� ������������ root)

make pending-patches
KERNEL_DIR=/usr/src/linux/

���������� KERNEL_DIR ������ ��������� ���� �
�������� ������� ������ ����. ������ ��� /usr/src/linux/. ���� ��������
������ � ��� ����������� � ������ �����, ��,
��������������, �� ������ ������� ���� ����.

Note

����� �������������� ��������� ���������
���������� � ����������, ������� ����������� ������
� ������ ����, �� ��������� �������, ������ �� ��
������� �� ������ �������� �������:

make most-of-pom
KERNEL_DIR=/usr/src/linux/

� �������� ���������� ��������������� ������� � ���
����� ������������� ������������� �� ���������� �������
������� �� ����, ��� � ���� netfilter ���������� patch-o-matic. ����� ����������
��� «��������» �� patch-o-matic, ��� ����� ���������
��������� �������:

make patch-o-matic
KERNEL_DIR=/usr/src/linux/

�� �������� ����������� � �� ����� ��������� ������� ��
������ «��������» �� ���� ��� �� ������
������������� ���-����, ��������� ���� «��������»
����� ��������� ������������ � �������, � ��������� — ���
���������� ��������� ���� ��������� ����.

Note

�� ������ ������ ���������� ���������� ����,
������� ������� ������ ����� � ����� ����������
���, ������ patch-o-matic ��������
������������� ���������� ����������, � � ��� ������
����� ���������� ������� ���������� �� ���. ������
��������� �� ��������, ���� �� ��������� ���
������� � ���������� ����� ���������� �������.

����� ���������� ����������, ��� ���������� �����
����������� ����, ������� � ���� ������ ��� �������������
����������. �� �������� ������� ��������� ����������������
����, ��������� ������������� ���������� ������ �����
�������� ������������. � ��������, ����� ��������� �
����������� ���� �� ��� ��� ���� �� �� ��������� ���������
iptables.

��������� ������ iptables, ��������� �������:

make
KERNEL_DIR=/usr/src/linux/

���� � �������� ������ �������� ����� ���� ��������, ��
������ ���������� ��������� �� ��������������, ����
���������� �� Netfilter mailing list, ��� ���
������ ������. ��� �� ������� ���������, ��� ����� ����
������� ���� ����������� ��� ���������, ��� ��� ����� ��
���������. ���� ��� �� ������� — ������������ ������������
���������, �������� ��� �������. ��� ���������� � ���������
«����».

���� ��� ������ ������, �� ������������� �� ������ �
��������� ����������� ������� (binaries), ��� ����
��������� ��������� �������:

make install
KERNEL_DIR=/usr/src/linux/

�������, ��� �����-�� ������� �� ��������! ������ ���
������������� ������ iptables ��� �����������
����������� ����������� � �������������� ����, ���� �� ��
��� ��� ����� �� �������. �������������� ���������� ��
��������� ������ �� ������� � ����� INSTALL.


2.3.2. ��������� � Red Hat 7.1

RedHAt 7.1, � ������������� ����� 2.4.x ��� ��������
����������������� netfilteriptables. ������, ��� ����������
�������� ������������� � ����������� ��������������, ��
��������� �������� ����� ipchains. ������ �� �������
�������� — ��� ������� ipchains � ��������� ������ ����
iptables.

Note

������ iptables � Red Hat 7.1
������ �������� �, �������� �������� �������� �����
���������� ����� ����� ������.

��� ������ ����� ��������� ipchains, ����� �������������
�������� ��������������� ������� � �������. ����� ��������
�����, ��� ����������� �������� ����� ��������� ������ �
������ ��������� /etc/rc.d/. ��������� �������,
�������� ��������� ��������:

chkconfig —level 0123456 ipchains
off

� ���������� ���������� ���� �������, � ��������� ������
������, ����������� �� ����� � �������� /etc/rc.d/init.d/ipchains, ������ S
(������� ��������, ��� ������ �������� ������������ ��
������� �������) ����� ������� �������� K (�� ����� Kill,
������� ��������� �� ��, ��� �������� ������������, ���
���������� ������ �������. ����� ������� �� ������������
������ ��������� ������� � �������.

������ ipchains ��-�������� �������� �
������. ������ ���� ��������� �������, ������� ���������
���� ������:

service ipchains stop

� � ���������� ���������� ��������� ������ iptables. ��� �����, ��-������,
���� ������������ � �������� ������� ������������ �������,
�� ������� ����� ���������� ���� ������. ������ ��� ������
2, 3 � 5. �� ���� ������� �� �����:

  • 2. ��������������������� ����� ��� ��������� NFS ���
    �� �� �����, ��� � 3, �� ��� ������� ���������.

  • 3. ������������������� ���������������������
    �����.

  • 5. X11. ������ ������� ������������ ���
    �������������� �������� Xwindows.

����� ��������� iptables �� ���� ������� �����
��������� �������:

chkconfig —level 235 iptables
on

������� ��������� �� �������, �� ������� �� ���������
������� iptables: ������� 1 —
�������������������� ����� ������, ��� ������� ������������
� ���������� �������, ����� �� «���������»
«�������» �������. ������� 4 — ������ �� ������
��������������. ������� ���������� 6 — ��� �������
��������� ������� ��� ���������� ��� ������������
����������.

��� ��������� ������� iptables ������� �������:

service iptables start

����, �� ��������� iptables, �� � ��� ���� ��� ���
�� ������ �������. ����� �������� ����� ������� � Red Hat
7.1 ����� ����� ����� ������, ��-������: ���������� ����
/etc/rc.d/init.d/iptables, �� ����
������ ����� ���� ���������� �������� — ��� ����������
iptables �� RPM-������� ��� ���� ������� ����� �������, �
��-������: ������� ������� � ��������� �� �������� iptables-save, ����������� �����
������� ������� ����� ������������� ����������������� ���
�������� �������.

� ������, ���� �� ������� ������ ������� ���������
������ � iptables, �� ��� ����������
������� �� � ������ start ��������
/etc/rc.d/init.d/iptables (��� ��������� ������ ���
�������� �������) ��� � ������� start(). ��� ����������
�������� ��� ��������� ������� — ������� ���������������
��������� � ������ stop) ��� � ������� stop(). ��� �� ��
�������� ��� ������ restart � condrestart. ������� ��� ���
���������, ��� � ������ ���������� iptables �� RPM-������� ��� �����
�������������� ���������� �� ����, �� ������ ������� ���
���������, ��������� � ���� /etc/rc.d/init.d/iptables.

������ ������ �������� ������ ����������������. ��
������������ ��������� ����. ��� ������ — �������� �������
� ���� ��� ���������������, ����� ������� iptables, ������ ��� ��� ���
����������������. ����� ��������� ������� iptables-save. ��� �������
������������ ������� iptables-save >
/etc/sysconfig/iptables
. � ����������, ���� �����
������ ����� �������� � ����� /etc/sysconfig/iptables, �������
������������� ������������ ��� ������� ������� iptables.
������ �������� ��������� ����� ������ ����� ������ �������
service iptables save, �������
��������� ��������� ��������������� �������. ������������,
��� ������������ ����������, �������� iptables �� rc.d
����� ��������� ������� iptables-restore ��� ��������
������ ������ �� ����� /etc/sysconfig/iptables.

� �������, � ���������� ���������, ������� ���� ��
������� ������ ������ ipchainsiptables. ��� ���������� �������
��� ����, ����� ������� �� «����������» ������
����� iptables � ����� �������������.
�������� ������� ������ iptables ���������� ����������
������ � ��� ������, ���� �� ����������� ��������� ��
�������� �������. ���� � ���, ��� RPM ������
��������������� � ��������� ���� ����� ������ ������,
��������� �� �������� �������, � ������� ����� ����� ��
«��������» ������. ����� ��������� �������������
���������� ������ iptables ��������� ���������
�������:

rpm -e iptables

����������� ������� ������ � ipchains, ��������� ���������
���� ����� � ������� ����� ��� �������� ������.

rpm -e ipchains


����� 3. ������� ����������� ������
� �������

� ���� ����� �� ���������� ������� ����������� ������ �
������� � ������ �������. ��� ���������� ����� ����� ����� ���
��� �������, ����� �� ������� ������� ���� ������ ������,
�������� ����� � ������ ������ ����� ���������� ����� ��������
��� DNAT, SNAT � ������� �� TOS.


3.1. ����� ���������

����� ����� �������� �� ��� ����������, �� �� ������
�������� �� ������� ����������, ���������������
��������������� ��������� � ����� ���������� � ����. �����
����� �������� ��� ������ � ����� ���������� ���� ����������
����������, ���� �������������� �� ������ ������. �������
���������� ������ ���������� ����:

������� 3-1. ������� �������� ����������
�������

��� ������� ������� ����������
1 ������ (�.�. ��������)
2 ������� ��������� (��������, eth0)
3 mangle PREROUTING ������ ��� ������� ������������ ���
�������� ��������� � ��������� ������, �������� ���
��������� ����� TOS � ��..
4 nat PREROUTING ��� ������� ������������ ��� ����������
������� ������� (Destination Network Address
Translation
). Source Network Address
Translation
����������� �������, � ������
�������. ������ ���� ���������� � ���� ������� �����
������������� ������ � �������������� �������
5 �������� ������� � ����������
�������������, �.�. � ���� ����� �������� ���� ������
����� — ���������� ���������� ��� �� ������ ����
����.
6 mangle FORWARD ����� ����� �������� � ������� FORWARD ������� mangle,
������� ������ �������������� ������ � ��������������
�������, ����� ���������� ������ ��������� ���������
� ��������� ������ ����� ����� ������� ��������
������� � �������������.
7 Filter FORWARD � ������� FORWARD �������� ������ ��
������, ������� ���� �� ������ ���� ��� ����������
����������� ������� ������ ����������� �����. ��
���������, ��� ����� ��� ������� �������� ������� �
����� ������������, ����������� ���������� ���
�������������� ��� ��������� ������ ����������.
8 mangle POSTROUTING ��� ������� ������������� ��� ��������
��������� � ��������� ������ ��� ����� ���� ���
������� ��������� ������� � �������������.
9 nat POSTROUTING ��� ������� ������������� � ������
������� ��� Source Network Address
Translation
. �� ����������� �� ��� ����������
��� ������ �� �� �������������. ����� �� �����������
� ����������� (Masquerading).
10 �������� ������� ��������� (��������,
eth1).
11 ������ (����� ����� LAN).

��� �� ������ ������, ����� �������� ��������� ������,
������ ��� �� ����� ������� �����. �� ������ �� ��� �����
����� ���� ����������, ���� �� ������� iptables ��� ��� ���� ���, �� ���
������� ������� ���������� iptables. ��������, ��� ��� �����
���� �������, ����������� ��� ��������� ����������� ��� ����
���� ���������. ������� FORWARD �������� ��� ������, �������
�������� ����� ��� ����������/ ������. �� ����������� �������
INPUT ��� ���������� ���������� �������, ��� ���� ������ ��
��������! ����� ��� ������� �������� ������ �� ������,
������� ������������� ������� �����!

� ������ ���������� ������� �������� ������,
���������������� ���������� ��������/����������:

������� 3-2. ��� ����������
����������

��� ������� ������� ����������
1 ������ (�.�. ��������)
2 ������� ������� ��������� (��������,
eth0)
3 mangle PREROUTING ������ ������������ ��� ��������
��������� � ��������� ������, �������� ��� ���������
����� TOS � ��.
4 nat PREROUTING �������������� ������� (Destination Network Address
Translation
). ���������� ������� �����
����������� ������ � �������������� �������.
5 �������� ������� � �������������.
6 mangle INPUT ����� �������� � ������� INPUT ������� mangle. �����
�������� ��������� � ��������� ������ ����� ��� ���
�� ����� ������� ���������� ����������.
7 filter INPUT ����� ������������ ���������� ���������
�������. �������, ��� ��� �������� ������,
������������ ���, �������� ����� ��� �������,
���������� �� ���� � ������ ���������� ���
���������.
8 ��������� �������/���������� (�.�.,
���������-������ ��� ���������-������)

����� �������, ��� �� ���� ��� ������ ���� ����� �������
INPUT, � �� ����� FORWARD.

� � ���������� �� ���������� ������� �������� �������,
��������� ���������� ����������.

������� 3-3. �� ��������� ���������

��� ������� ������� ����������
1 ��������� ������� (�.�.,
���������-������ ��� ���������-������).
2 �������� ������� � �������������. �����
�������� ���� ������ ����� ������ — �� ����� �����,
����� ����� ������� ��������� � ��.
3 mangle OUTPUT ����� ������������ �������� ��������� �
��������� ������. ���������� ���������� � ����
������� ����� ����� ���������� �����������.
4 nat OUTPUT ��� ������� ������������ ��� ����������
������� ������� (NAT) � �������, ��������� ��
��������� ��������� �����������.
5 Filter OUTPUT ����� ����������� ���������
�������.
6 mangle POSTROUTING ������� POSTROUTING ������� mangle �
�������� ������������ ��� ������, ������� ������
������� ��������� � ��������� ������ ����� ���, ���
�� ������� ����������, �� ��� ����� �������� �������
� �������������. � ��� ������� �������� ��� ������,
��� ����������, ��� � ��������� ���������� ����������
�����������.
7 nat POSTROUTING ����� ����������� Source Network Address
Translation
. �� ������� � ���� �������
����������� ���������� ������� �� ���������
������������� �������� ��������. ������ � ����� �����
������������� ������, �������� �������� ��-���������
DROP.
8 ������� ��������� (��������, eth0)
9 ������ (�.�., Internet)

������ �� �����, ��� ���� ��� ��������� ��������
����������� �������. ������� ���� ����� ��������
������������� ���:

���� ������� ���� �������� ����� ������������� � �������
����������� ������� ����� ��������� �������. � ������ �����
�������� ������� � ������������� (routing decision) ���
������, ��������������� ������� ����� ������������ � �������
INPUT, ��������� — � ������� FORWARD.

�������� �������� ����� �� ��� ����, ��� ������, � �������
���������� �� ����������, ����� ���������� ��������� ��������
������ ���������� (DNAT) � ������� PREROUTING ������� nat �
�������������� ���������� ������������� � ������ ����� �����
����������� � ����������� �� ������������� ���������.
��������� — ��� ������ �������� ����� ������� �
������� �� ���� ��� ����� ��������. ���� ���� ����������� DNAT � �� �� ����, ������ �����
������, �� �� ��� ����� ��������� �������� �� ��������.

Tip

� �������� rc.test-iptables.txt
�� ������� ����� �������������� ���������� � �������
����������� �������.


3.2. ������� Mangle

��� ��� ����������� ����, ��� ������� �������������,
������� ������� ��� �������� ��������� � ��������� �������
(mangle — ��������, ��������. ����. �����.). �.�. � ����
������� �� ������ ������������� ���� TOS (Type Of Service) � �.�.

Caution

��� ��� ��������� ���, ��� � ���� ������� ��
������� ����������� ������ ���� ����������,
���������� ��� �������������� ������� (DNAT, SNAT,
MASQUERADE)
.

� ���� ������� ����������� ��������� ������
����������������� ��������:

  • TOS

  • TTL

  • MARK

�������� TOS ��������� ��������� ����� ����
Type of Service � ������. ��� ����
������������ ��� ���������� ������� �������� ������������
������, �.�. ������ �������� ������� �������������. ������,
������� ��������, ��� ������ �������� � ����������������
������������ �� �������������� ���������� ��������������� �
���������. ������� �������, �� ������� �������� ���������
����� ���� ��� �������, �������� � ��������, ������ ��� ��
��������, ������� ���� ����������� ��� ����, ����� ����
������� ������������ ������� ��� ������ ��������.

�������� TTL ������������ ��� ���������
�������� ���� TTL (Time To Live) ������. ���� ����
�������� ���������� ����� ��������. �� ����� �����������
������������ �������� ����� ����, ����� ������ ��� ����������
�� �������� ���������� ����������� (Internet Service
Providers). ���� � ���, ��� ��������� ���������� ����� ��
����� ����� ���� ����������� ����������� �����������
������������. � ����� ��� �������� ��������� �������� TTL ���������� ������� � ����������
��� ��� ���� �� ��������� ����������� ����, ���� ���������
«�����» �� ����������� ��� ���������.

�������� MARK ������������� �����������
����� �� �����, ������� ����� ����� ���� ��������� �������
��������� � iptables ��� ������� �����������, ��������
iproute2. � �������
«�����» ����� ��������� �������������� �������,
������������ ������� � �.�.


3.3. ������� Nat

��� ������� ������������ ��� ���������� ��������������
������� ������� NAT (Network Address Translation). ���
��� ����������� �����, ������ ������ ����� �� ������ ��������
����� ������� ���� �������, ���������� ������� ��� ����������
����������� �� ���� ����������� ������� � ������
�������������. ��� ���� ������� ���������� ��������:

  • DNAT

  • SNAT

  • MASQUERADE

�������� DNAT (Destination Network Address
Translation) ���������� �������������� ������� ���������� �
���������� �������. ������� �������, ���� ���������
������������ ��������������� ������� �� ������ ������,
�������� �� ��������� � ���������� �������.

SNAT (Source Network Address
Translation) ������������ ��� ��������� �������� �������
�������. � ������� ����� �������� ����� ������ ���������
��������� ����, � ������ � ��������� ������������ ������� IP
����� ����� ������������ ��������� ���� ��� ������ �
��������. � ���� ������ ����������, � ������� SNAT, ������������� ����������
������ � �������� �������������� �������, ��� ����� �����
����������� ��������� ����������� � �������� � ��������� �
����������� � ��������� ����.

���������� (MASQUERADE) ����������� � ��� ��
�����, ��� � SNAT, �� � ������� �� ���������,
MASQUERADE ���� ����� �������
�������� �� �������. ���������� ��� ������, ��� ������ ���,
����� ��������� ���������� ����� �������� — ������������
������ IP ������ ��� ���������� � �������� ��������
����������, � �� ����� ��� ��� SNAT IP ����� �����������
���������������. ������, ��������� ������ �������, MASQUERADE ����� �������� � �������
� ������������ IP �������, �.�. ����� �� ������������� �
��������, ������ ����� PPP, SLIP ��� DHCP.


3.4. ������� Filter

��� ������� �� ��������, � ���� ������� ������ �����������
������ ������ ��� ���������� ���������� �������. ������ �����
������������ �����, ���� ����������� (�������� ACCEPTDROP ��������������), � �����������
�� �� �����������. ������� ��, �� ����� ���������������
������ � � ������ ��������, �� ��� ������� ���������� ������
��� ���� ����������. � ���� ������� ����������� �������������
����������� �� ������������ ��������, ������ ��� ��������,
������� �� ����������� ���� � ���� �����, ������ �����������
������ � �������� �� ��������.


����� 4. �������� �����������
���������

� ������ ����� ��� �������� ����� ������� ���������
����������� ��������� ������� (state machine). �� ��������� ��
� ��� ������ ��������� ���������� ������ ������������� � ������
���������, � �������������� ����� ������ ������������ �����
���������� ��������.


4.1. ��������

�������� ����������� ��������� (state machine) ��������
��������� ������ iptables � � ���������������� �� ������ ��
��� ����������, ��������� ���������� �������� ����������
����������� ����������. ������ ������������� ���������� �����
�� �������� ������ ��� «�������� �����������
���������» (state machine). � ������ ����� ��� ��������
����� �������������� ��� ��������. ������������ ����������
������ ��� ����, ����� netfilter ��� ��������� �����
���������� � ��������� ������� ����������� ����������.
������� ������������� ��������� ��������� ����� ��������
������ ������ �� ��������� � �������������, ������� �� �����
��������� ������ ���������.

� �������� iptables, ���������� ����� ����� ���� �� 4-�
������� ���������: NEW, ESTABLISHED, RELATEDINVALID. ������� �� ����������� ��
������ �� ��� ����� ��������. ��� ���������� ������������
�������, ����������� �� �� ���������, ������������ ��������
—state.

����������� ���������� ������������ ����������� ����� �
������������ ���� — �������������� (conntrack). ���
������������� ����� ���� ������������� ��� ������������
������ ����, ��� � ���������� ������ � �����. � �����������
������� ��� �������� ����� ����������� ���������� �
����������, ��� ��, ������� ���������� ������������
��-���������. ������� ������������ �������� � ����
����������� ��������� ����������, �������� TCP, UDP ��� ICMP. ��������� ��� ���������� �����
������������ ��� ������������� � ����������� ��������
��������� ����������. �������� — ���������� �� ��������� UDP ���������� ���������������� ��
IP-������� � ������ ��������� � ���������.

� ���������� ������� ���� ������� �����������
���������/���������� ��������� �������������� �������.
������, ����� ���� ��� ����������� ���������� ���� �������� �
������ iptables/netfilter, ���������� � ���� ������. �������
� ���, ��� ������������ �� � ��������� ��������� �����������
�� ���� ������� ��� ��������� �������������� � ������� ���
�������� ���������. �� ������ ��������� ����� ��� ��������
����������� ����������. �������������� ����������� ������,
���� ������������ �������.

����������� ���������� ������������ � ������� PREROUTING, �������� ������, �����
������ ��������� ���������� ���������� �� �����������, � ����
������ ����������� ������������ � ������� OUTPUT. ��� ��������, ��� iptables
���������� ��� ����������, ��������� � ������������
���������, � �������� ���� �������. ����� ��������� �������
�� ����������� ���������� ������ ����� �� ������, �� �
������� OUTPUT ��� ������������� ���������
NEW, � ����� ������������ �����
������, �� ��������� ���������� � ������� PREROUTING ���������� �� ESTABLISHED, � ��� �����. ���� ��
���������� ��������������� �����, �� ��������� NEW ������������� ������� ������ ��
������ � ������� PREROUTING. ����� �������, �����������
��������� ������� ������������ � �������� ������� PREROUTINGOUTPUT ������� nat.


4.2. �������
�������������

������ ���������� ������� �������������, ������� �����
����� � ����� /proc/net/ip_conntrack. �����
���������� ������ ���� �������� ����������. ���� ������ ip_conntrack ��������, �� �������
cat /proc/net/ip_conntrak ������
������� �����, ��������:

tcp  6 117 SYN_SENT src=192.168.1.6 dst=192.168.1.9 sport=32775 \
     dport=22 [UNREPLIED] src=192.168.1.9 dst=192.168.1.6 sport=22 \
     dport=32775 use=2
    

� ���� ������� ���������� ��� ����������, ������� ��������
�������������, �� ����������� ����������. ������, ��� �����
������� — ��� �������� ���������, � ������ ������ — tcp.
����� ������� ��������� ����� � ������� ����������
�������������. ����� ���� ������� �����, ������������
«����� �����» ������ � ������� (�.�. ����������
������, ����� ������� ���������� � ���������� ����� �������
�� �������). ��� ������ ������, ������ � ������� �����
��������� ��� 117 ������, ���� ������� ����� ��� ����������
����� �� ���������� �� ������ ������. ��� ����������� �������
������������ ������ ����� ������ ����������, ��� ��������
����� ��������������� � �������� ��-��������� ��� ���������
���������. ��� ����� ����������� �� 1 ������ �������. �����
������� ����������� ��������� ����������. ��� ������ �������
��������� ����� �������� SYN_SENT. ����������
������������� ��������� ��������� ���������� �� ��������.
�������� SYN_SENT ������� � ���, ���
����� ������ ���������� ����������� ������������ ����� TCP SYN. ����� ����������� ������
����������� � ����������, ���� ����������� � ����������.
����� �� ����� �������� ����� [UNREPLIED], ������� �������� �
���, ��� ��������� ������� ����� ��� ���������� ��� �� ����.
� ������� ���������� �������������� ���������� �� ����������
������, ��� IP ������ �����������/���������� (�� �� �����,
������ ������������ �������, ��������� ��������� ��������
�����), �� �� �������� � ������.

������ � ������� ����� ��������� ��� ��������, ��� ���
���������� � ������������ ������ linux/include/netfilter-ipv4/ip_conntrack*.h.
�������� ��-��������� ������� �� ���� ���������. ������ ��
IP-���������� — TCP, UDP ��� ICMP ����� ����������� ��������
��-���������, ������� ���������� � ������������ ����� linux/include/netfilter-ipv4/ip_conntrack.h.
����� �������� �� ����������� �� ���� ���������, ����� �����
������������� ������ �� ���������� � �����������.

Note

������ �������, � patch-o-matic, ��������� �������
tcp-window-tracking, ������� �������������
����������� �������� �������� ���� ��������� �����
����������� ����������, �.�. ��������� �������� ��
«�� ����». ����� ������� ����������
����������� ��������� ��������� ��� �������������
���������� ����.

��������� �������� � ������� ������������
��������� �������, ����� ������� /proc/sys/net/ipv4/netfilter.
������ �������� �������� �� ��� ���������� /proc/sys/net/ipv4/netfilter/ip_ct_*.

����� ��������� ������ ������ ������������ ������ ���� [UNREPLIED] � ������� ��� ������
[ASSURED]. ���� ���� �������� �
���, ��� ���������� ����������� �������� � ��� ������ ��
����� ������ �� ���������� ����������� ���������� ����������
������������ ����������. ������������ ���������� �������,
������� ����� ����������� � ������� ������� �� ��������
��-���������, ������� ����� ���� ����������� ������� �������
ipsysctl � ��������� ������� ����. ��� ������ ��� 128 �� ���
�������� ������������� 8192 �������, ��� 256 �� — 16376. ��
������ ���������� � �������� ��� �������� ����������
���������� /proc/sys/net/ipv4/ip_conntrack_max.


4.3. ��������� � ������������
������������

��� �� ��� ��������� ��������, � ������������ ����, �
����������� �� ���� ���������, ������ ����� ����� ���������
��������� ���������. ������, ��� ���� ������ ����� �����
������ 4 ���������. � �������� ��������� ������ ������������
��������� —state. ����������� ��������
��������� NEW, ESTABLISHED, RELATEDINVALID. � �������, ����������
����, �������������� ������ �� ��������� ���������.

������� 4-1. �������� ��������� � ������������
������������

��������� ��������
NEW ������� NEW �������� � ���, ���
����� �������� ������ ��� ������� ����������. ���
��������, ��� ��� ������ ����� � ������ ����������,
������� ������ ������ �������������. �������� ����
������� SYN ����� ���������� ������
������� ��� ������� ����������, �� �� ������� ������
NEW. ������, ����� ����� �
�� ���� SYN ������� � ��� �� �����
�������� ������ NEW. ��� ����� ��������
������������ �������� � ��������� �������, �� �����
��������� � ������ ��������, �������� �����
���������� «����������» ����������,
«����������» ������� ������������� ��� �
�������, ����� ������� ���������� ��� �����, �� ����
���������� �� ���� �������.
RELATED ��������� RELATED ���� �� �����
«������». ���������� �������� ������
RELATED ���� ��� ������� �
������ �����������, ������� ������� ESTABLISHED. ��� ��������,
��� ���������� �������� ������� RELATED �����, ����� ���
������������ �� ��� �������������� ����������,
�������� ������� ESTABLISHED. �������
�������� ����������, ������� ����� ���������������
��� RELATED, ��������
���������� FTP-data, ������� ��������
��������� � ������ FTP control, � ��� �� DCC ����������, ���������� ��
IRC. �������� �������� �� ��,
��� ����������� ���������� TCP � ��������� �� ����������
UDP ������ ������ � ��������
���������� � ���������� ����� ������� ������ TCP ��� UDP ������� � ������� �������
������� ����������� ��������������� ������� ���
���������� ������.
ESTABLISHED ��������� ESTABLISHED ������� � ���,
��� ��� �� ������ ����� � ����������. ����� ���������
��������� ESTABLISHED ����������
������ ��� ���������. ������������ ����������,
������������� � ����������, ����������� � ���, ���
��� �������� � ��������� ESTABLISHED ����������
����� ���� ���� ������� ����� � ������� �� ���� �����
�� ������� ���� (�����). ����� ��������� ������
��������� ���������� NEW ��� RELATED����� ��������� ��
ESTABLISHED.
INVALID ������� INVALID ������� � ���, ���
����� �� ����� ���� ��������������� � ������� ��
����� ����� ������������� �������. ��� �����
����������� �� ������ ��������, �������� ��� ��������
������ ��� ��� ��������� ICMP-��������� �� ������,
������� �� ������������� ������ ���� ����������
����������. �������� ��������� ��������� ���� ��
���������� �������� DROP � ����� �������.

��� ������ ��������� ����� �������������� � ��������
—state. �������� �����������
��������� ��������� ������� ����������� ������ � �����������
������. ������ ����������� ��������� ��� ����� ���� 1024,
����� ���������� �������� ������ � ��������� ����, ������ ��,
��� ������� ��������� ����������� ���������, ������������� �
���� ������, ��������� ��������� �����������
«���������» ������ ������ ��� ��������� (���������)
�������, �������� ������� ������������ ���������� �����.


4.4. TCP ����������

� ���� � � ����������� �������� �� ������� ����������
�������� ��������� � ������� �� ��������� ������ �� ����
������� ���������� TCP, UDPICMP, � ��� �� �������� ������, �����
�������� ���������� �� ����� ���� ��������������� ��
�������������� � ����, �������������, ����������. ������
������������ � ��������� TCP, ��������� �� ����� ���������
������������� ������������ � ��������� ��������� �����������
��������� � iptables.

TCP ���������� ������ ���������������
��������� ���� �������, ������� �������������� �
������������� ����������, ����� ������� � ���������� �����
������������ ������. ������ ���������� � �������� SYN ������, � ����� �� �������
���������� SYN/ACK ����� � ������������
������������ ���������� ����� ACK. ����� ����� ���������� ���������
������������� � ������� � �������� ������. ����� ����������
������: «� ��� �� ������������ ����������?». �
���������������� ��� �������� ������.

��� ���� ����� ����������, ����������� ��������
����������� ���������. ��������� �� ������� ����, ���
�������� ��� ������ ������������ ����������. ��� ������,
������������, � ����� ������ ������������, ���������� ��
������ �� ����� ������������ ����������. ������, ��� ������
������������ «������» ������ (SYN) �����, �� ����������� ��� ������
NEW. ��� ������ ����� �������������
�������� ������ ����� (SYN/ACK), �� ���������� �������������
������ ESTABLISHED. ����� ������ ������
�����? ������ ����������. ����� ���� ����� ������, �� ������
��������� �������� ��������� ���� ������� �� �������� NEWESTABLISHED, � �� �������� �������
���������� ������ ������ �� �������� ESTABLISHED � ��� ����� ��������
���������. � ��������, ���� �� ������������ ��������� �������
���������� ��� NEW, �� ���������� ��� ������� ��
������� �� ���������� ���������� � «������� �����»,
���� �������� �� ��������� ����������� NEW ������� � ��������� ����. �
����� ������ ���� ��� �������� ����� �������, ��������� �
������������ ���� TCP ���������� ����� ��� �������������
���������, ����������� � ������������ ������������. � �����
������ ��� ������������� ������������ RFC 793 — Transmission Control
Protocol
�� �������� 21-23. ����� �������� ��� ����
����� ��������������� ���� ����.

� ����� ������ ������������ ��� �������� ����������
������, ������ ���� ���������� � ����� ������ ����, �� ���
�������� ��������� �������. ���������� ������� ���������
��������� ���������� � ������� /proc/net/ip_conntrack. ����� ��������
������� ������ SYN.

tcp      6 117 SYN_SENT src=192.168.1.5 dst=192.168.1.35 sport=1031 \
     dport=23 [UNREPLIED] src=192.168.1.35 dst=192.168.1.5 sport=23 \
     dport=1031 use=1
  

��� ������, ������ � ������� �������� ������ ���������
���������� — ��� ������� ���� �������� ������ SYN (���� SYN_SENT), �� ������� ������
���� �� ���� (���� [UNREPLIED]). ����� ���������
������-������, ���������� ����������� � ��������� ����������
���������:

tcp      6 57 SYN_RECV src=192.168.1.5 dst=192.168.1.35 sport=1031 \
     dport=23 src=192.168.1.35 dst=192.168.1.5 sport=23 dport=1031 \
     use=1
  

������ ������ �������� � ���, ��� ������� ������ ����� SYN/ACK. �� ���� ��� ����������
����������� � ��������� SYN_RECV. ��� ��������� �������
� ���, ��� ����� SYN ��� ������������ ���������
���������� � � ����� �� ���� ������ �����-������������� (SYN/ACK). ����� ����, ��������
����������� ��������� «������» ������, ��������� �
����� ������������, ������� ���� [UNREPLIED]. � ������� �����
�������� ��������������� ACK-������, � ��������� ������������
����������

tcp      6 431999 ESTABLISHED src=192.168.1.5 dst=192.168.1.35 \
     sport=1031 dport=23 src=192.168.1.35 dst=192.168.1.5 \
     sport=23 dport=1031 use=1
  

���������� ��������� � ��������� ESTABLISHED (�������������). �����
������ ���������� ������� ����� ��� ����������, � ����
��������� ���� [ASSURED] (���������).

��� ��������, TCP ���������� �������� �����
��������� ���������.

��� ����� �� �������, ���������� �� ����������� �� ��� ���
���� �� ����� ������� ��������� ����� ACK. �������� �������� — ��� ��������
��������� ���������� ������� �������� ����������. ����� ����,
���� ���������� �����������, �� ��� ����� ���� �������
��������� ������ RST (�����). � ���� ������ ����������
����� ������� �� ��������� ����������������� �������.

��� ��������, ���������� ����������� � ��������� TIME_WAIT, �����������������
�������� ��-��������� ������������� 2 �������, � �������
�������� ��� �������� ����������� ������� ����� ����������.
��� �������� ������ ���� «�������� ��������»,
������� ���� ����������� ������ �������, «�������»
�� ��� ��� ���� �������������� (�������).

���� ���������� ����������� �� ��������� ������ RST, �� ��� ����������� � ���������
CLOSE. ����� �������� ��
������������ �������� ���������� ��-��������� ���������������
������ 10 ������. ������������� �� ������ RST �� ���������� � ����������
����������� ����� ��. ����� ���� ������� ��� ������
���������� ���������. � ������� ���� ���������� ������
��������� ���������� ��������� ���������� � ���������������
�� ������� ���������.

������� 4-2. Internal states

��������� ����� ��������
NONE 30 �����
ESTABLISHED 5 ����
SYN_SENT 2 ������
SYN_RECV 60 ������
FIN_WAIT 2 ������
TIME_WAIT 2 ������
CLOSE 10 ������
CLOSE_WAIT 12 �����
LAST_ACK 30 ������
LISTEN> 2 ������

��� �������� ����� ��������� ���������� �� ������ � ������
����, ����� ����, ��� ����� ���� �������� ����� ���������
�������� ������� /proc (���������� proc/sys/net/ipv4/netfilter/ip_ct_tcp_*).
�������� ��������������� � ����� ����� �������, ��� ��� �����
3000 �������� 30 ������.

Note

�������� �������� �� ��, ��� �� �������
������������, �������� ����������� ��������� ����� ��
���������� ��������� ������ TCP �������. ��� ������� — ���
�� ������ ������, ��������� ��������� NEW �������������, ��
������ ������� SYN.

��� �������� ������������� ����� ���� ������������
��� ����������� ������������� (firewalling), �� ���
������ �������� ��������� ����, � �������
������������ ������ ���� ���������� ��� ����� �����.
��� �������� ����� �������� ����������� � ������� ������ �� �������� NEW � ��
���������� ����� SYN
���������� ����� �������� �
�������
. �������������� ��������� �������
���� �������� ����� ������� ��������� ������� tcp-window-tracking ��
patch-o-matic, �������
������� ��������� �������� ������� � ����������� ��
�������� TCP window.


4.5. UDP ����������

�� ���� �����, UDP ���������� �� ����� ��������
���������. ����� ������� ��������� ������, �������� �� ���
������� � ���, ��� ���� �������� �� ���������������
������������ � �������� ����������, �� ����� �������
���������� — ���������� ���������� �� �����������
����������� �������. ������ ��� ���������� UDP, ���������� ������� ����� � �����
������� ��� ���� ����������. ������, ���� � ���� �������� ���
��� �������� ���������� ��������� ����������. ���� ����������
������� ����, ��� �������� ������������ ���������� � �����
������ �������������.

�� ������� �����, ��� ��������� UDP ���������� ������������ ����� ���
�� ��� � ��������� TCP ����������, � ����� ������ ��
����������������� ������������. ������� �� ��� ��������
��������� �����, ���� �� ������ ������. ��� ������ ���������
�� ������, ����������� ����� �������� ������� ������ UDP.

udp      17 20 src=192.168.1.2 dst=192.168.1.5 sport=137 dport=1025 \
     [UNREPLIED] src=192.168.1.5 dst=192.168.1.2 sport=1025 \
     dport=137 use=1
  

������, ��� �� ����� — ��� �������� ��������� (udp) � ���
����� (��. /etc/protocols ����. �����.). ������ �������� —
���������� «����� �����» ������ � ��������. �����
������� �������������� ������, ���������� ����� ���������� —
��� ������ � ����� ����������� � ����������. ����� �� �����,
��� ��� ������ ����� � ������ (���� [UNREPLIED]). � ��������� ������
������ � ����� ����������� � ���������� ���������� ������.
������� ����� ������ �� ��������� ���������� 30 ������.

udp      17 170 src=192.168.1.2 dst=192.168.1.5 sport=137 \
     dport=1025 src=192.168.1.5 dst=192.168.1.2 sport=1025 \
     dport=137 use=1
  

����� ���� ��� ������ «������» ����� �� ������
�����, ���������� ��������� ESTABLISHED (�������������),
������������ ������� �� ���������� ������ ������� �
���������� ����� [UNRREPLIED] �, ����� ����,
������� ��� ������ ���� ������ 180 ��������. ����� �����
����� ������ ���������� ���� [ASSURED] (���������
����������), ������� ��� ������ ����. ���� [ASSURED] ��������������� ������
����� ����������� ���������� ���������� ������� �����
����������.

udp      17 175 src=192.168.1.5 dst=195.22.79.2 sport=1025 \
     dport=53 src=195.22.79.2 dst=192.168.1.5 sport=53 \
     dport=1025 [ASSURED] use=1
  

������ ���������� ����� «���������». ������ �
������� �������� ����������� ��� �� ��� � � ����������
�������, �� ����������� ����� [ASSURED]. ���� � ������� 180
������ ����� ���������� �� ������� ���� �� ���� �����, ��
������ ����� ������� �� �������. ��� ���������� ���������
���������� �������, �� ��� ������ ���������� ��� �����������
����������. «����� �����» ������������� �� �������
����������� ���������� ������ � ��� ��������� ������, �����
������������������� � ���� ��������� ��������, ���
����������� � ��� ���� ��������� ����� ����������
���������.


4.6. ICMP ����������

ICMP ������ ������������ ������ ���
�������� ����������� ��������� � �� ���������� �����������
����������. ������, ���������� 4 ���� ICMP �������, ������� ��������
�������� ������, ������� ��� ����� ����� ��� ���������:
NEWESTABLISHED. � ���� �������
��������� ICMP Echo Request/Echo Reply, ICMP Timestamp Request/Timestamp
Reply
, ICMP Information Request/Information
Reply
ICMP Address Mask Request/Address Mask
Repl
y. �� ��� — ICMP Timestamp Request/Timestamp Reply
ICMP Information Request/Information
Reply
��������� ����������� � �������, � �����������
�������, ����� ���� ������������� �������� (DROP). ��������� �� �������
����.

��� ����� �� ����� �������, ������ ��������� Echo Request (���-������) � �������,
������� (������) ������������ ������������ ��� NEW. �� ���� ������ ������ ��������
������� Echo Reply, � ������ �����
������������ ��� ������� ��������� ESTABLISHED. ����� �����������
������� ������ (Echo Request) � ip_conntrack ���������� ������:

icmp     1 25 src=192.168.1.6 dst=192.168.1.10 type=8 code=0 \
     id=33029 [UNREPLIED] src=192.168.1.10 dst=192.168.1.6 \
     type=0 code=0 id=33029 use=1
  

��� ������ ��������� ���������� �� �������, ������������
���������� TCPUDP, ���� ����� ��� �� ������������ �
�������� ��������� � ����� �������� � ������ ����������� �
���������, �� ����� ���������� ��� ����� ���� — type, code � id. ���� type �������� ��� ICMP, ���� code — ��� ICMP. �������� ����� � ����� ICMP ���������� � ���������� ���� ICMP. � ��������� ����
id �������� �������������
������. ������ ICMP-����� ����� ���� �������������.
����� ��������, � ����� �� ICMP-������ �������� �����, ��
����������� � ����� ������ ���� �������������, ���������
����, ���������� ����� ��������� ���������� � ����� �� �����
������ ������ �����.

��������� ���� — ���� [UNREPLIED], ������� ����������
��� �����. �� ��������, ��� ������ ������ ����� � ����������.
����������� ������ ���������������� ���������� ������ ������.
���� ���������� ������ ����������� � ����������. ��� ��������
���� � ���� ICMP ������, �� ��� �������������
���������� ��������� ���������� ������ ICMP Echo Reply. �������������
������-������ ��� ��, ��� � � ������ �������.

����� ������ ������������ ��� ��� ESTABLISHED. ������, �� �����, ���
����� �������� ������ ������, ����� ��� ���������� ��� ������
�� ���������, ������� ����� ����������� ������ �����
netfilter, ������ � ������� ������������� ������������.

� ����� ������ ������ ��������������� ��� NEW, � ����� ��� ESTABLISHED.

Note

�������� ��� ����, ��� ����� ������ ������
��������� �� ����� ��������������� (������
����������� � ����������, ���, ��� � �������������) �
���������� � ������ � ������� �������������, ���
����������� � ��� ���� ��������� ����� �������.

ICMP ������� ����� �������, ��-���������, 30 ������. �����
�������, � ����������� �������, ������ ����������. �����
�������� ����� �������� � /proc/sys/net/ipv4/netfilter/ip_ct_icmp_timeout.
( ���������, ��� ���������� ���� /proc/sys/net/ipv4/netfilter/ip_ct_*
���������� �������� ������ ����� ���������
«�������» tcp-window-tracking �� patch-o-matic
����. �����.).

������������ ����� ICMP ������������ ��� ��������
��������� � ���, ��� ���������� � ��� ��� ���� UDP ��� TCP �����������. ������ � ���� ���
����� ����� ������������ ��� ��������� (RELATED) � ������������
�����������. ������� �������� ����� ������� ��������� ICMP Host Unreachable ��� ICMP Network Unreachable. ��� ������
����������� ��� ������� ����������� � ����� ���� ����� ����
���� ��� ���� ����������, � ���� ������ ���������
������������� ������ ��������������� ICMP �����, ������� ����� ���������
��� RELATED. �� ������� ���� ��������
��� ��� ����������.

� ���� ������� ���������� ���� ���������� ������ ��
���������� (SYN �����). �� ����������� ������
NEW �� �����������. ������, � ����
������ �������, ���� ����������� �����������, ������� ������
���������� ����� ICMP Network Unreachable. ������������
���������� ���������� ���� ����� ��� RELATED, ��������� ��� ���������
������ � �������, ��� ��� ����� ������������ ����� �������
�������, ������� ����� ������� ��������� ����������. ���
��������, ���������� ��������� ������ � �������, ���������
��� ������� ���������� ���� �������� ��������� �� ������.

�� �� ����� ���������� � � UDP ������������ — ����
�������������� �������� ��������. ��� ��������� ICMP, ������������ � ����� �� UDP ����������, ��������������� ���
RELATED. ��������� �� ���������
�������.

���������� UDP ���������� �� ������. ����������
������������� ������ NEW. ������ ������ � ���� ��������
(������������ ��� ��������), ������� ������� ������������
��������� ICMP Network Prohibited. ����������
���������� ��� ��������� ��� ��������� � �������� UDP �����������, ����������� ���
������ RELATED � �������� �������. �����
���� ������ � ������� ������������� ������������, � ������
������������ �������� ����������.


4.7. ���������
��-���������

� ��������� ������� �������� ����������� ��������� ��
����� ���������� �������� ������ �, ��������������, �� �����
������� ��������� ��������� ����� ����������. � ���� ������
�� ��������� � ��������� ��-��������� ���������. ���������
��-��������� ������������, �������� ��� ������������
���������� NETBLT, MUXEGP. ��������� ��-�������� �� ������
����� � ������������ UDP ����������. ������� ������
������������� ������ NEW, � ���� ����������� — ������
ESTABLISHED.

��� ������������� ��������� ��-���������, ��� ���� �������
������������ ���� � �� �� �������� ��������, ������� �����
�������� � /proc/sys/net/ipv4/netfilter/ip_ct_generic_timeout.
��-��������� ��� �������� ����� 600 ��������, ��� 10 �������
� ����������� �� ���� �������, ��� ����� ����� ��������,
�������� ����� ���������� ��������������� �� ������������
������.


4.8. ����������� �����������
����������

������� ��� ����������� ����������, ���������� �����������
������� ����� ������. ������� ����� ������� ��������� ICQ, IRCFTP. ������ �� ���� ���������� �����
�������������� ���������� � ���������� � ������� ������
������. �������������� ���������� ����������� �����
���������� ������� ����������� �������������� ���������������
�������.

� �������� ������� ������� ���������� �������� FTP. �������� FTP ������� ��������� ���������
����������, ������� ���������� «������� ����������
FTP» (FTP control session). ��� ����������
������ � �������� ����� ������, ��� �������� �������������
������ ����������� �������������� �����. ��� ���������� �����
���� ��������� ��� ����������. ��� �������� ���������
���������� ����� �������� FTP ������� ����� ����� � IP ����� ��� ����������. ����� �����
��������� ����, ������ ���������� � ��������� ����� �������
���� ���� � ������� 20 (��������� ��� FTP-Data) � �������� ������ �����
������������� ����������.

�������� ������� � ���, ��� ���������� ������ �� ����� ��
���� �������������� ������������, ��������� ��� ���������� �
��� ���������� ����� ������� ������ ������. ��-�� �����
���������� �� �������� ������� ����������� � ��������� ������
�������.

������� �������� ������� � ���������� ������������
���������������� ������ �����������, ������� �����������,
����������� ��� ������� ���������, ���������� � �������
������ �������, ������������ � ������ ������ ����������. ���
�������� ������ ����������, ��������������� ������ ���������
��������� ������������ ���������� � ������� ���������������
������ � ������� ������������� �� �������� RELATED, ��������� ���� ����������
����� �����������. ������� ���� �������� ������� ����������
��������� ����������.

��������� FTP ��������� ��������������� �������.
������ �������� ������ ������� �� ��������� ������, � ������
���������� ������� IP ����� � ����� ����� ���
�����������. ������ ���������� ���� 20-� ���� (FTP-data) � ���������� ����� ������� �
�������� ����������� ������. ���� ��� FTP ������ ��������� ��
������������, �� ��� ����������� ���� ��������������� ������
��� ����, ����� ������ ���� ����������� �������� �� ��������.
�� �� ����� �������� ������, ����� �� ������ ���������� �����
������������� ������ ������������ ����������� � HTTPFTP �������� � �������� � ������� ���
��������� �����. ������� ���� ���������� ��� �����������
��������� ���������� FTP.

��������� ��������������� ������ ��� �������� � ������
����. ���� ���� ����� ������, �� � ������ ���� ��������
��������������� ������ ��� ���������� FTPIRC. ���� � ����� ������������ ���
������������ ���������������� ������, �� ��� �������
���������� � patch-o-matic, ������� ��������
������� ���������� ��������������� ������� ��� �����������
����� ����������, ��� ntalk ��� H.323. ���� � ����� �� �� ����� ��,
��� ��� �����, �� � ��� ���� ��� ��������: �� ������
���������� � CVS iptables, ���� ������� ���������������
������ ��� �� ��� ������� � patch-o-matic, ���� ������ ����� �
������� � �������������� netfilter � ������ � ��� — �������
�� �������� ������ � ����������� �� �� � �������. ���� � ���
�� ��������� �������, �� �������� ��� ������� ��������� Rusty Russell’s Unreliable
Netfilter Hacking HOW-TO.

��������������� ������ ����� ���� �������������� ��� �
���� ������������ ������� ����, ��� � ���������� ������� �
�����. ���� ��� �������������� ��� ������, �� �� ������
��������� �� ��������:

modprobe ip_conntrack_*
  

�������� �������� �� ��, ��� �������� �����������
��������� �� ����� �������� ��������� � ���������� �������
������� (NAT), ������� ��� ����� �������������
������� ���������� �������������� �������, ���� �� ����������
����� ����������. ��������, ��� �� ���������� ����������
������� � ����������� FTP ����������, ����� ��� ���������
��� �� � ��������������� ��������������� ������ NAT. ����� ��������������� ������� NAT ���������� � ip_nat_, �
������������ � ����������� �� ������. � ������ ������ ������
���������� ip_nat_ftp. ��� ��������� IRC ����� ������ ����� ���������� ip_nat_irc. ���� �� ������ ����������
������� � �������� ��������������� ������� �������������,
��������: ip_conntrack_ftpip_conntrack_irc.


����� 5. ���������� � ��������������
������� ������� ������

� ������ ������ iptables ������ ��� ����� �������
�������, �������� ���� ��� ���������� ����� ���� � ��������
�������� ������. ���������� ��� iptables-saveiptables-restore. ������ �� ���
���������, � ������ ��������������� ������ ������ �/�� �����.
�� ������ ������� ���� � ������� ������ ����� �� ������� �����
��������� ��������� �������� (shell), � ��� �� �������
��������� ���� ����.


5.1. �����

���� �� ������ ������������� ������ iptables-saveiptables-restore ������� � �������
�������� �������� � ���������� ������� ������� ������.
������� ����������, ��������� � ���������� ������� ������ ��
��������� ��������� �������� ������� � ���, ��� �������
iptables �������� ����� ������ ��
������������ ���� � ������������ ������������, ���������,
��������� ��� �������� ������� �, �������, ���� ����� ������
���������� ������� � ������������ ����. ���
������������������ �������� ����������� ��� ������� �������,
������� ����������� ��� ���������� � ������ ������.

��� �������� ����� �������� � ������� iptables-saveiptables-restore ������� iptables-save ���������� �����
������ � ������� ��������� ���� � ������ �������. �������
iptables-restore ��������� �����
������ �� �����. ������� ������������ ���� ������ ������� �
���, ��� ��� ���������� ����������/�������������� �����
������ ������ �� ���� ���������. iptables-save «� ����
�������» �������� �� ������������ ���� � ���������� �
���� ���� ����� ������, � iptables-restore ��������� �� �����
� ������������ �� ���� ��������� � ������������ ���� �����
������ ��� ������ �������. ��� ������� ������� — ������
����, ����� ���������� �������� ����� ��� � ���� ��� ����
����� �������� ����� ������, � ����� ����� �������� ��� �
������������ ���� �� ������� ����� ���, ����� ������
��������� ����� ������ � ����, � ����� ��������� ��� ��
�����, ��� ���� ����� ����������� ������� � ���� �����
�������� ������ �� ����� ������������ ������.

�� ��� ��������� ������, ��� ��� ������� �����
������������ ��� ��� �������, �������� ���� ��� ����������
��������� �������� ������ ������. ������ ������������� ����
������ ����� � ���� ������������� �������, ������� ��
���������� � ��������� �������.


5.2. � ������

� ��� ����� ��������� �����������, ��� iptables-restore ����� ������������
������ ���� ��������. ���� �� ����� � ��������� ����� —
������� �� ������. � ���� � ������� ������� ����������
iptables-restore. ����� ���� �����
������� — ����������� ���� ������, ����� ���������� ��������
������������ IP-����� � �� ������ �������� ��� �������� �
���� ������� �� ����� �������� �������. ������ ��� �������� �
������� iptables-restore �����������
����������.

��� ���� �� ������� ����� ���������� �������� ���������
������, ������� ���������� �������� IP-������ � �����
��������� ��� � ����� ������ (��������, � ������� sed) �� ����� ���������� ���������
�����. ����� ��� ����������� ������� ��������� ����, �
������� ������������ ��������� � ������� ����� ����������� �
������� iptables-restore. ������ �����
������� ������� ��������� ���� �������� — ��� ��������
���������� �� ������� iptables-save ��������� ��� �����
��������, ��������� �������, ��������� ����� � ��������� ���
iptables-restore. ������ —
�������� ��������� �������.

��� ���� ������� — ������� � ����� ��� iptables-restore ������ �����������
�������, � ����� � ������� ���������� ������� ���������
������� � ������������� �����������. ������� �� �� ���
������, ��� ��� ������� ����� �� ��������� ��� � ������. ���
�������� ��������� � ���, ��� iptables-restore �� ����� ������
�������� ��� ������ � ����������� ����������� IP-������� �
������ ��� �������, ����� ��� ����������� �����������
�������� ����� ������ � ����������� �� ������������ ������� �
�.�..

��� ���� ���������� iptables-restoreiptables-save � ���, ��� ��
���������������� �� ������ ������������� ���������. ��������
������� � ���, ��� �� ������ ���������� ����� ���������, ���
������ ����� ��������� � ������� ������ ������ � ����
����������. �������, ��� ������������� ���������, �����
�����������, ��������� ��� �������� �� ������ ����������� �
����������� ���������� ����� ������. �������� �� ���������
������������� ��������� �������, � ��� �� ������������
���������� � ������������� ��� ��� �����������, �������
��������� �������� � ����������� �������, ���������� �����
���������� ���� ��������� ����� �������� � ��������.


5.3. iptables-save

������� iptables-save, ��� � ��� ��������,
������������� ��� ���������� �������� ������ ������ � ����,
������� ����� ����� ���� ����������� �������� iptables-restore. ��� ������� �����
������ � ������������� � ����� ����� ��� ���������.

iptables-save [-c] [-t table]

������ �������� -c (��������� ������������ �����
������� ������� —counters) ���������� iptables-save ��������� �������
��������� ���� � �������. ��� ������ ��������� �������
����������� ��� ������ ���������, ������� �����
�������������� ��� �������� ����������. ��-���������, ���
������� ��� ����� -�, ���������� ��������� ��
������������.

� ������� ����� -t (����� ������� ������� —table) ����� ������� ��� �������
��� ����������. ���� ���� -t �� �����, �� ����������� ���
�������. ���� �������� ������ ������ ������� iptables-save � ������, ����� �����
�� �������� �� ������ �������.

# Generated by iptables-save v1.2.6a on Wed Apr 24 10:19:17 2002
*filter
:INPUT ACCEPT [404:19766]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [530:43376]
COMMIT
# Completed on Wed Apr 24 10:19:17 2002
# Generated by iptables-save v1.2.6a on Wed Apr 24 10:19:17 2002
*mangle
:PREROUTING ACCEPT [451:22060]
:INPUT ACCEPT [451:22060]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [594:47151]
:POSTROUTING ACCEPT [594:47151]
COMMIT
# Completed on Wed Apr 24 10:19:17 2002
# Generated by iptables-save v1.2.6a on Wed Apr 24 10:19:17 2002
*nat
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [3:450]
:OUTPUT ACCEPT [3:450]
COMMIT
# Completed on Wed Apr 24 10:19:17 2002

������, ������������ � ������� #, �������� �������������.
����� ������ ���������� � ������� * (���������), ��������:
*mangle. ����� ������� �����
������� ������� �������� ������� � ������. �������� �������
������������ � ������� :<chain-name>
<chain-policy>
[<packet-counter>:<byte-counter>], ���
<chain-name> — ��� �������� ������� (�������� PREROUTING), <chain-policy>
— �������� ��-��������� (�������� ACCEPT). ��������� ��������
������� �������� ��������� ������� � ����, �� ����� ��������,
������� �� �������� � ���������� ���������� ������� iptables -L -v. �������� ������
������� ��������� �������� ����� COMMIT, ������� ��������, ��� �
���� ����� ����� ������ ��� ������ ������� ����� ������� �
������������ ����.

������ ���� ������� ��� �������� ���������� ������� ������
������, ������������ �������� iptables-save. ���� �������
��������� ���������� ���������� ������ ������ (Iptables-save ruleset)
:

# Generated by iptables-save v1.2.6a on Wed Apr 24 10:19:55 2002
*filter
:INPUT DROP [1:229]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
[0:0] -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
[0:0] -A FORWARD -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT
[0:0] -A FORWARD -i eth1 -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT
[0:0] -A OUTPUT -m state --state NEW,RELATED,ESTABLISHED -j ACCEPT
COMMIT
# Completed on Wed Apr 24 10:19:55 2002
# Generated by iptables-save v1.2.6a on Wed Apr 24 10:19:55 2002
*mangle
:PREROUTING ACCEPT [658:32445]
:INPUT ACCEPT [658:32445]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [891:68234]
:POSTROUTING ACCEPT [891:68234]
COMMIT
# Completed on Wed Apr 24 10:19:55 2002
# Generated by iptables-save v1.2.6a on Wed Apr 24 10:19:55 2002
*nat
:PREROUTING ACCEPT [1:229]
:POSTROUTING ACCEPT [3:450]
:OUTPUT ACCEPT [3:450]
[0:0] -A POSTROUTING -o eth0 -j SNAT --to-source 195.233.192.1
COMMIT
# Completed on Wed Apr 24 10:19:55 2002

�� ������� ����� ��������� �������� ��������� -c — ����� ������ �������� � �
������ �������� ������ ������� ������� �����, ������������
���������� ��������� ������� � ����. ����� ������, ��� �����
������ ������� iptables-save ������ �� �����������
�����, �������, ��� ���������� ������ � ���� ������� ������
��������� �������� ���:

iptables-save -c >
/etc/iptables-save

��� ������� ������� ���� ����� ������, ������ � ����������
���������, � ���� � ������ /etc/iptables-save.


5.4. iptables-restore

������� iptables-restore ������������ ���
�������������� (��������) ������ ������, ������� ����� ���
�������� �������� iptables-save. ����� ������ �������
�������� �� ������������ ����� � �� ����� ��������� ��� ��
����� ��������. ������� ����� ��������� ���������:

iptables-restore [-c] [-n]

���� -c (����� ������� ������� —counters) ����������
��������������� �������� ���������.

�������� ����� -n (����� ������� ������� —noflush) �������� iptables-restore � ���, ��� �������
������ ���� ��������� � ���������. ��-��������� �������
iptables-restore (��� ����� -n) ������� ���������� ������ �
������� ����� ��������� ������ ������ ������.

��� �������� ������ ������ �������� iptables-restore �� ����� �����
���������� ��������� ���������, �� �������� �����������:

cat /etc/iptables-save | iptables-restore
-c

� ���������� ���������� ���� ������� ���������� ����� /etc/iptables-save ����� ���������
�������� cat � ��������������� ��
����������� ���� ������� iptables-restore. ����� ���� ��
�������� ��� ����� ��� ������, � ������� ������� �����
������������ �������� ������ ������ �� �����, �� ��� �������
�� ����� ����, ������� ������� �������� ����������� ������
����� ����� ������� ��� ���� �������.

����� ���������� ���� ������� ����� ������ ������
����������� � ��� ������ ��������. ���� ��� �� ���, �� ������
����� �� ��������� ������ ��� ������ �������.


����� 6. ��� ������� �������

� ������ ����� ����� ����������� ������� ����������
����������� ������ ��� iptables. ������ ������, ������� ��
���������� � �� ��� ���� �������, ������ ��������� ���������
�������. �� ��� �� ������� �������� �������� � ��������
(targets) � ������� �������� ����� ����������� �������� (�.�.
���������� ������).


6.1. ������

��� ��� ���������� ����, ������ ������� — ��� ������,
���������� � ���� �������� ������������, ��������� �� �����
��� �������� �������, � ��������, ������� ����������
��������� � ������ ���������� ��������. � ����� ���� �������
������������ �������� ���:

iptables [-t table] command [match]
[target/jump]

����� �� ������������, ��� �������� �������� (target/jump)
������ ������ ��������� � ������, ������, ����� ������� �����
������������. ��� �� �� �� ����, �� ���� ����� ��� �����
����������� ������ ����� ������ ������ ������.

���� � ������� �� ���������� ������������ [-t table], ��
�� ��������� �������������� ������������� ������� filter, ���� �� ��������������
������������� ������ �������, �� ��� ��������� ������� ����.
������������ ������� ��� �� ����� ��������� � ����� �����
������ �������, ������ ����� ��� ����� ���������� ���������
�������� ������� � ������ �������.

�����, ��������������� �� ������ �������, ������ ������
�������. ���� ������������� ������� ���, �� ������� ������
������ ������ ������. ������� ���������� �������� iptables,
��������: �������� �������, ��� �������� ������� � �����
�������, ��� ������� ������� � �.�.

������ match ������ �������� ��������, �� �������
������������ ��������� �� ����� ��� �������� ����� �������
��� ���. ����� �� ����� ������� ����� ������ �������� —
IP-����� ��������� ������ ��� ����, IP-����� �����
����������,����, ��������, ������� ��������� � �.�.
���������� ��������� ������������� ���������, �� �� ���� —
��������� �����.

� ������� target ���������, ����� �������� ������ ����
��������� ��� ������� ���������� ��������� � �������. �����
����� ��������� ���� �������� ����� � ������ ������� ������,
«��������» ����� � ������ ��� ����, ������ ��
�������� ��������� �� ������ � �.�.


6.2. �������

����� -t ��������� �� ������������
�������. �� ��������� ������������ ������� filter. � ������ -t ����������� ��������� �����.

������� 6-1. �������

������� ��������
nat ������� nat ������������ �������
������� ��� �������������� ������� ������� (Network Address Translation).
����� ��� ������� �������� ������ ������ ����� ��
������. �������������� ������� �������������
����������� �� ���� ����������� �������. ��� ���� ��
��������, ������ �� ������� �� �� ������ ������������
�����-���� ���������� � ���� �������. ������� PREROUTING ������������ ���
�������� ��������� � ������ �� ����� � ����������.
������� OUTPUT ������������ ���
�������������� ������� � �������, ���������
������������ ������ �����������, ����� ���������
������� � �������������. � ��������� ������� � ����
������� — POSTROUTING, �������
������������ ��� �������������� ������� ����� �������
�� � ����.
mangle ��� ������� ������������ ��� ��������
��������� � ��������� �������. �������� ����� �������
��������� ���� TTL, TOS ��� MARK. �����: �
���������������� ���� MARK �� ����������, �� �
������ ���� ��������� ���������, ������� ������������
������ ����� ��� ����� ��� ����������� �����
����������, ��� ��� ������ ������� � ���������� ��
������ ����������� (� ������ �� ������ �����������)
����� ������������ ��� ���� � ����� �����. �������
����� ���� ������� PREROUTING, POSTROUTING, INPUT, OUTPUTFORWARD. PREROUTING ������������ ���
�������� ��������� �� ����� � ����������, �����
��������� ������� � �������������. POSTROUTING ������������ ���
�������� ��������� �� ������ �� �����������, �����
�������� ������� � �������������. INPUT — ��� ��������
��������� � ������ ����� ��� ��� ��� ����� ��������
���������� ���������� ������ �����������. OUTPUT — ��� ��������
��������� � ������, ����������� �� ���������� ������
�����������. FORWARD — ��� ��������
��������� � ���������� ������ ����� ������� ��������
������� � �������������, �� ����� ��������� ���������
������� � �������������. ������, ��� ������� mangle �� � ���� ������ ��
������ �������������� ��� �������������� �������
������� ��� ������������ (Network Address Translation,
Masquerading
), ��������� ��� ���� ����� �������
������� nat.
filter ������� filter ������������ �������
������� ��� ���������� �������. ��� �������, ����� ��
����� ��������� DROP, LOG, ACCEPT ��� REJECT ��� ����� ����
�����������, ������� ������� � ������ ��������.
������� ��� ���������� �������. ������ — FORWARD, ������������ ���
���������� �������, ������ ��������� �����
����������. ������� INPUT �������� ������, �������
������������� ��������� ����������� (�����������). �
������� OUTPUT — ������������ ���
���������� ��������� �������, ���������������
������������ �� ����� �����������.

���� �� ����������� �������� ������� ���� ���������
������. ������ �� ��� ������ �������������� ������ � �����
�����, � �� ������ ��� ��������. ��������� �������������
������ ����� �������� � ���������� ������ ����������� � ����,
����������� �� ���. �������, � ����� ������� ����������� ������ �
�������
, �� ��������� ����������� �� ����.


6.3. �������

���� ���������� ������ ������ � ������� �� �������������.
����������� ������ �� �������� iptables ��� �� ������������
�������. ������ �������������� ���� �� ���� �������� —
���������� ������ ������� � ������� ��� ��������
������������� ������� �� ��� ��� ���� �������. �����
��������� �������, ������� ������������ � iptables.

������� 6-2. �������

������� -A, —append
������ iptables -A INPUT …
�������� ��������� ����� ������� � �����
�������� �������.
������� -D, —delete
������ iptables -D INPUT —dport 80 -j
DROP
, iptables -D INPUT 1
�������� �������� ������� �� �������. �������
����� ��� ������� ������, ������ — ����� ��������
�������� ��������� � ������ -D (��. ������ ������),
������ — ���������� ����� �������. ���� ��������
�������� ���������, �� ��������� �������, �������
����� � ���� ���� ��������, ���� �������� �����
�������, �� ����� ������� ������� � �������� �������.
���� ������ � �������� ���������� � 1.
������� -R, —replace
������ iptables -R INPUT 1 -s 192.168.0.1
-j DROP
�������� ��� ������� �������� ���� �������
������. � �������� ��� ������������ �� ����� �������
����� ������.
������� -I, —insert
������ iptables -I INPUT 1 —dport 80 -j
ACCEPT
�������� ��������� ����� ������� � �������.
�����, ��������� �� ������ ������� ��������� �����
�������, ����� ������� ����� �������� ����� �������,
������� ������� ����� ������ ����� ��� ������������
�������. � ������� ����, �����������, ��� ������
������� ������ ���� 1-� � ������� INPUT.
������� -L, —list
������ iptables -L INPUT
�������� ����� ������ ������ � �������� �������,
� ������ ������� �������������� ����� ������ ��
������� INPUT. ���� ��� ������� ��
�����������, �� ��������� ������ ������ ��� ����
�������. ������ ������ ������� �� �������
�������������� ������ � �������, �������� -n, -v, � ��.
������� -F, —flush
������ iptables -F INPUT
�������� ����� (��������) ���� ������ ��
�������� ������� (�������). ���� ��� ������� �
������� �� �����������, �� ��������� ��� �������, ��
���� ��������. (������� �� ���� ��������, ��� ����
�� ������� ������� ������ -t (—table), �� �������
������� ������������ ������ � ������� filter, ����. �����. )
������� -Z, —zero
������ iptables -Z INPUT
�������� ��������� ���� ��������� � ��������
�������. ���� ��� ������� �� �����������, ��
��������������� ��� �������. ��� ������������� �����
-v ��������� � ��������
-L, �� ����� ����� ������ �
��������� ��������� �������, �������� ��� ��������
������� �������. ����������� ���������� �������������
������ -L-Z. � ���� ������ �����
����� ������� ������ ������ �� ����������, � �����
���������� ��������� ���������.
������� -N, —new-chain
������ iptables -N allowed
�������� ��������� ����� ������� � ��������
������ � �������� ������� � ���� ����������� �������
��������� ����� ������� � ������ allowed. ��� ������� ������
���� ���������� � �� ������ ��������� �
������������������ ������� ������� � �������� (������
��� DROP, REJECT � �.�.)
������� -X, —delete-chain
������ iptables -X allowed
�������� �������� �������� ������� �� ��������
�������. ��������� ������� �� ������ ����� ������ �
�� ������ ���� ������ �� ������ ������� �� ���������
�������. ���� ��� ������� �� �������, �� �����
������� ��� ������� �������� ������� �����
����������.
������� -P, —policy
������ iptables -P INPUT DROP
�������� ������ �������� ��-��������� ���
�������� �������. �������� ��-��������� ����������
��������, ����������� � ������� �� �������� ���
�������� �� ������ �� ������ � �������. � ��������
�������� �� ��������� ����������� ������������
DROPACCEPT.
������� -E, —rename-chain
������ iptables -E allowed
disallowed
�������� ������� -E ��������� ��������������
���������������� �������. � ������� ������� allowed ����� ������������� �
������� disallowed. ��� ��������������
�� �������� ������� ������, � ����� ������
������������� ��������.

������� ������ ���� ������� ������. ������ ���������
������ ����� ����������� � ������� ������� iptables -h ���, ��� ���� �����,
iptables —help. ��������� �������
����� �������������� ��������� � ��������������� �������.
���� ���������� ������ �������������� ������ � �����������
��������� �� ��������. ��� ���� ��������, ��� ����� ��
���������� �������������� ������, ������� ������������ ���
���������� ��������� (matches) ��� �������� (targets). ���
����� �� ����� ��������� �����.

������� 6-3. �������������� �����

���� -v, —verbose
�������, � �������� ������������ —list, —append, —insert, —delete, —replace
�������� ������������ ��� ���������
��������������� ������ �, ��� �������, ������������
��������� � �������� —list. � ������
������������� � �������� —list, � ����� ����
������� ���������� ��� �� ��� ����������, ��������
������� � ���� ��� ������� �������. ������ ������
��������� ������������ ����� ����� ���� ����� ��� �
���������� ��������� K (x1000), M (x1,000,000) � G
(x1,000,000,000). ��� ����, ����� ��������� �������
—list �������� ������
����� (��� ������������ ����������) ���������
��������� ���� -x, ������� ������ ����.
���� ���� -v, —verbose ������������ �
��������� —append, —insert, —delete ��� —replace, �� ����� �������
��������� ����� � ������������� ��������.
���� -x, —exact
�������, � �������� ������������ —list
�������� ��� ���� ����� � �������� ������
��������� �� ������ �������� ��� ���������� � ���
������������� ���������� K, M, G. ���� ����
������������ ������ � �������� —list � �� �������� �
������� ���������.
���� -n, —numeric
�������, � �������� ������������ —list
�������� ���������� iptables �������� IP-������
� ������ ������ � �������� ���� ������������ �������
������������� �� � ������������� �����. ������ ����
������������ ������ � �������� —list.
���� —line-numbers
�������, � �������� ������������ —list
�������� ���� —line-numbers ��������
����� ������ ������� ����� ��� ����������� ������
������ �������� —list. ����� ������
������������� ������� ������� � �������. ���� ����
������������ ������ � �������� —list.
���� -c, —set-counters
�������, � �������� ������������ —insert, —append, —replace
�������� ���� ���� ������������ ��� ���������
���������� �������� ��������� ������� � ���� �
�������� �������� ��� �������� ������ �������.
��������, ���� —set-counters 20 4000 ���������
������� ������� = 20, � ������� ���� = 4000.
���� —modprobe
�������, � �������� ������������ ���
�������� ���� —modprobe ����������
������� �������� ������ ����. ������ ���� �����
�������������� � ������, ����� ������ ���� ���������
��� ���� ������ (search path). ���� ���� �����
�������������� � ����� ��������.


6.4. ��������

����� �� ��������� ����������� �� ��������� ���������
�������. � ������ ��� �������� �� ���� �����. ������ — ����� �������� ������� �����
�������������� � ����� ��������. ������ — TCP �������� ������� �����������
������ � TCP �������. ������ — UDP �������� ������� �����������
������ � UDP �������. ��������� — ICMP �������� ��� ������ � ICMP ��������. � ������� ����� —
����������� ��������, ����� ��� state, owner, limit � ��.


6.4.1. ����� ��������

����� �� ���������� ����� ��������. ����� ��������
��������� ����������� � ����� ��������, ��� �� ������� ��
���� ��������� � �� ������� ��������� ������� ����������. �
���� ������ � ��������� ����� �������� —protocol �������� �� ��, ��� ��
������������ � ��������� ����������� �� ���������
�����������. ��������, �� ������ ������������ TCP ��������, ����� ��� ����������
����� ������������ � �������� —protocol �������� � ��������
��������������� ����� ���������� �������� ��������� — TCP.
������ �������� —protocol ��� �� ���� ��������
���������, ������� ������������ ��� �������� ����
���������.

������� 6-4. ����� ��������

�������� -p, —protocol
������ iptables -A INPUT -p
tcp
�������� ���� �������� ������������ ���
�������� ���� ���������. ��������� ���������� �����
���� TCP, UDPICMP. ������ ����������
����� ���������� � ����� /etc/protocols. ������
�����, � �������� ����� ��������� � ������ ��������
����� ���������� ���� �� ���� ��������������
����������, � ����� �������� ����� ALL. � ��������
��������� ����������� ���������� ����� — �����
���������, ��� ��������, ��������� ICMP
������������� ����� 1, TCP — 6 � UDP — 17.
������������ ����� �������� ���������� � �� �������
�� ������ ���������� � ����� /etc/protocols, ������� ���
����������. �������� ����� ������������ � ������
����������, ����������� ��������, �������� ���:
udp,tcp (���� ����� � ��������� ��
����������� �������� ������ ����������, ��� ��
����� ��� ���� �� ������� ��� �������! ������, man iptables ����
�����������, ��� � ������ �������� ����� ����
������ ������ ���� ��������. ����� ���� ���
���������� ������� � patch-o-matic? ����. �����.)
����
������� �������� ���������� �������� �������� 0, ��
��� ������������ ������������� ������������� ALL,
������� ��������������� �� ���������, �����
�������� —protocol ��
������������. ��� ���������� �������� ��������,
����� ������ ��������� (������� ����������)
������������ ������ !, �������� —protocol ! tcp
������������� ������ ����������, UDPICMP.
�������� -s, —src, —source
������ iptables -A INPUT -s
192.168.1.1
�������� IP-�����(�) ��������� ������. �����
��������� ����� ����������� ���, ��� �������� �
�������, ����� ��������������� ������������
IP-�����. � ����� ������� ����� � ����
address/mask, �������� ��� 192.168.0.0/255.255.255.0,
��� ����� ����������� �������� 192.168.0.0/24, �.�.
���������� ��������� �������� ������� ��� � �����,
������ !, ������������� ����� �������, ��������
���������� ���������, �.�. —source ! 192.168.0.0/24
�������� ����� ����� ����� ������� 192.168.0.x.
�������� -d, —dst, —destination
������ iptables -A INPUT -d
192.168.1.1
�������� IP-�����(�) ����������. �����
��������� ������ � ��������� —source, �� �����������
����, ��� ������������� ����� ����� ����������.
����� ��� �� ����� ���������� ��� ������������
IP-�����, ��� � �������� �������. ������ !
������������ ��� ���������� �������� ��������.
�������� -i, —in-interface
������ iptables -A INPUT -i
eth0
�������� ���������, � �������� ��� �������
�����. ������������� ����� �������� �����������
������ � �������� INPUT, FORWARDPREROUTING, � ����� ������
������� ����� �������� ��������� �� ������. ���
���������� ����� �������� �������������� �����
���������, ��� ����������� ������������� ��������
-i +. ��� � ������,
������ ! ����������� ��������� ����������. ���� ���
���������� ����������� �������� +, �� �������� ������ ���
����������, ������������ � �������� ������,
�������� -i PPP+ ���������� �����
PPP ���������, � ������ -i ! eth+ — �����
���������, ����� ������ eth.
�������� -o, —out-interface
������ iptables -A FORWARD -o
eth0
�������� ������ ��� ��������� ����������. ����
�������� ����������� ������������ ������ � ��������
OUTPUT, FORWARDPOSTROUTING, � ���������
������ ����� �������������� ��������� �� ������.
��� ���������� ����� �������� �������������� �����
���������, ��� ����������� ������������� ��������
-o +. ��� � ������,
������ ! ����������� ��������� ����������. ���� ���
���������� ����������� �������� +, �� �������� ������ ���
����������, ������������ � �������� ������,
�������� -o eth+ ���������� �����
eth ���������, � ������ -o ! eth+ — �����
���������, ����� ������ eth.
�������� -f, —fragment
������ iptables -A INPUT -f
�������� ������� ���������������� �� ���
��������� ������������������ ������, ����� �������,
������� ��� ������, ��� ��� ����������� ����������
���������/�������� ���� ��� ��������� ������, � ���
ICMP-������� ���������� �� ���. � �������
����������������� ������� ����� ������������� �����
�� ��� ����������, ��� ��� ��������� ������� �����
�� ������������� ������� ���������. ��� � ������,
����������� ������������� ������� ! ��� ��������
���������� ���������. ������ � ������ ������ ������
! ������ �������������� �������� -f, �������� ! -f. �������� ��������
���������� ��� «��� ������ ���������
����������������� ������� �/��� �������������������
������, �� �� ������ � ����������� ���������
����������������� �������».


6.4.2. ������� ��������

� ���� ������� �� ���������� ������� ��������, ������, ��
��������, ������� ������������ ������ � ����������
��������, �������� ��� �������� �������� —protocol tcp. �� �����������
���� ���������� ��� ������������� ������������ ����������,
��� TCP ��������, UDP ��������ICMP �������� (��� ���������� ����� ������ � ����������
� �������������� ������ �������� ����� -m tcp, �.�. � ��������� �����
�������� �� ����������, ������� ������ ������������ ���
���������� ����� ������, ���� ���-�� �� ���� — ��������
���� ��������� ����������� ����������. ����. �����.)
. �������� ����
���������� ����� ������������� � ����� ������� � �������
����� -m, -match, �������� -m tcp.


6.4.2.1. TCP ��������

���� ����� ��������� ������� �� ���� ��������� �
�������� ������ � TCP ��������. ����� ������������
��, ��� ����������� � �������� ��������� ��� ���������
—protocol tcp. �����: ��������
—protocol tcp �����������
������ ������ ����� ����������� ���������. ��� ����������
����������� ������������� ��� ��� tcp ���������, ��� � ��� udpicmp ����������. (� ������� �������� ���������� � ���
�������� ���� ����. �����.)
.

������� 6-5. TCP ��������

�������� —sport, —source-port
������ iptables -A INPUT -p tcp —sport
22
�������� �������� ����, � �������� ���
��������� �����. � �������� ��������� �����
����������� ����� ����� ��� �������� �������
������. ������������ ���� �������� � �������
������ �� ������� ����� � ����� /etc/services.
��� �������� ������� ������ ������� ������������
��������� �������. ������ ��� ����� ������ ���
������� ��������� ��������. ���� �� ��
����������� ��������� ������������ �� ������
������ ������, ������ ������� ���������� ����� �
�����, �� ��� ���������������� ������������
������ ������. ������ ������ ����� ���������� �
���� ��������� �� ������������ � �������������
�������, �������� —source-port 22:80.
���� ���������� ����������� ����, �.�. �����
�������� ������������ ��� —source-port :80, �� �
�������� ������ ��������� ����������� ����� 0.
���� ���������� ������������ ����, �.�. �����
�������� ������������ ��� —source-port 22:, �� �
�������� ����� ��������� ����������� ����� 65535.
����������� ����� ������ —source-port 80:22, �
���� ������ iptables �������� �����
22 � 80 �������, �.�. ��������� ���� ������ �����
������������� � —source-port 22:80.
��� � ������, ������ ! ������������ ���
��������. ��� �������� —source-port ! 22
������������� ����� ����, ����� 22. ��������
����� ����������� � � ��������� ������, ��������
—source-port ! 22:80.
�� �������������� ����������� ����������� �
�������� �������� multiport.
�������� —dport, —destination-port
������ iptables -A INPUT -p tcp —dport
22
�������� ���� ��� �������� ������, ��
������� ��������� �����. ��������� �������� � ���
�� �������, ��� � ��� —source-port.
�������� —tcp-flags
������ iptables -p tcp —tcp-flags
SYN,FIN,ACK SYN
�������� ���������� ����� � �����
tcp-������. ����� ��������� ���������������
��������, ���� �� ������������� ������ � ������
������ � ��������� ��������� ����������� ����� ��
������� ������. ��� ��� �������������� �������
��� �������� ��������� ������ � ������� ���� SYN ����������, � �����
FINACK ��������. � ��������
���������� �������� ����� ��������� ����� SYN, ACK, FIN, RST, URG,
PSH
, � ��� �� �����������������
�������������� ALLNONE. ALL — ������ ��� ����� � NONE — �� ���� ����. ���,
�������� —tcp-flags ALL NONE
�������� — «��� ����� � ������ ������
���� ��������»
. ��� � �����, ������
! �������� ��������
�������� �����: ����� ������ � ������ ������
������ ����������� ��������, ������� ������ ���
���������� �������.
�������� —syn
������ iptables -p tcp
—syn
�������� �������� —syn �������� �� ����
��������, �������������� �� ipchains. ��������
������������� ������ � ������������� ������ SYN � ����������� �������
ACKFIN. ���� ��������
���������� �������� —tcp-flags SYN,ACK,FIN
SYN
. ����� ������ ������������ ���
�������� ���������� TCP. ������������ �����
������, �� ������� ������������ ��� ��������
������� �� ����������, ������ ���� �������� ��
�������� ������������� ��������� ������� ��
����������. ��� � �����, �����������
�������������� �������� �������� !. ��� �������� ! —syn �������� — «��� ������, �� ����������
�������� �� ����������»
, �.�. ���
������ � �������������� ������� FIN ��� ACK.
�������� —tcp-option
������ iptables -p tcp —tcp-option
16
�������� ��������������� ������� �������
�������� ����� ����� ��������� �����, TCP �������� ��������
����� ��������� �����. TCP Option — ��� �����
��������� ������. ��� ������� �� 3 ���������
�����. ������ 8-�� ������� ���� ��������
���������� �� ������, ������������ � ������
����������. ������ 8-�� ������� ���� ��������
����� ���� �����. ���� ��������� ���������� ��
�����, �� ��������� �� ����������� ��������� ����
��������� ���������, ������, ������ ����� ��
����� ��������� ������ ���� � � ������, ���� ���
������� ���������������� ����� ������������
�����, �� ������ ����������� ����� ������ ����
(����� �������� ���������� �� ������ ����).
�����, ������� �� ����� ����� ������� TCP ���������, �����
������� ������������� ��� ������� �������� ���
TCP ���������. ��� �
�����, ����������� ������������� ����� ��������
������� !. ��������������
���������� �� TCP Options �� �������
����� �� Internet Engineering Task
Force


6.4.2.2. UDP ��������

� ������ ������� ����� ��������������� ��������,
����������� ������ ��� ��������� UDP. ��� ���������� ������������
������������� ��� �������� ���� ��������� —protocol udp. ����� ��������,
��� ������ UDP �� ������������� ��
������������� ����������, � ������� �� ����� ���������
������ ������� ���� ����������� ������ � ��������������
���������. ��������� UDP ������� �� ������� ������ ����
������������� �� ������� ����������. ���� ��� ��������,
�� ��� ������ �������� (�� ������� �������� ICMP ��������� �� ������). ���
������������ ������� ����������� �������� �����
�������������� ���������, � ������� �� TCP �������. �����: �������
���������� ������ �������� � �������� ������ ����, UDP ��� ICMP, ������� ��������� ��
���������������� �� ����������, ��� �� ������ ��� � � TCP ��������. �� ���� �� ���������
�������, � ��������� ������.

������� 6-6. UDP ��������

�������� —sport, —source-port
������ iptables -A INPUT -p udp —sport
53
�������� �������� ����, � �������� ���
��������� �����. � �������� ��������� �����
����������� ����� ����� ��� �������� �������
������. ������������ ���� �������� � �������
������ �� ������� ����� � ����� other/services.txt. ���
�������� ������� ������ ������� ������������
��������� �������. ������ ��� ����� ������ ���
������� ��������� ��������. ���� �� ��
����������� ��������� ������������ �� ������
������ ������, ������ ������� ���������� ����� �
�����, �� ��� ���������������� ������������
������ ������. ������ ������ ����� ���������� �
���� ��������� �� ������������ � �������������
�������, �������� -source-port 22:80.
���� ���������� ����������� ����, �.�. �����
�������� ������������ ��� —source-port :80, �� �
�������� ������ ��������� ����������� ����� 0.
���� ���������� ������������ ����, �.�. �����
�������� ������������ ��� —source-port 22: , ��
� �������� ����� ��������� ����������� �����
65535. ����������� ����� ������ —source-port 80:22 , �
���� ������ iptables �������� ����� 22 � 80
�������, �.�. ��������� ���� ������ �����
������������� � —source-port 22:80 .
��� � ������, ������ ! ������������ ���
��������. ��� �������� —source-port ! 22
������������� ����� ����, ����� 22. ��������
����� ����������� � � ��������� ������, ��������
—source-port !
22:80
.
�������� —dport, —destination-port
������ iptables -A INPUT -p udp —dport
53
�������� ����, �� ������� ��������� �����.
������ ���������� ��������� ���������� ���������
� �������� —source-port.


6.4.2.3. ICMP ��������

���� �������� ������������, ��� �������, ��� ��������
��������� �� ������� � ��� ���������� �����������. �� ��
�������� ����������� IP ���������, �� ����� � ���
���������������, ��������� �������� ������������
��������� ��������. ��������� ICMP ������� ����� ������ �� IP ���������, �� ����� � �������.
������� �������� ����� ��������� ����������� � ����
���������, ������� �������� ���������� � ���, ��� ��� ��
�����. ��������, ����� �� �������� ����������� �
����������� ������, �� �� ������� � ����� ��������� ICMP host unreachable. ������
������ ����� ICMP ���������, �� ������
���������� � ���������� ���� ICMP. ����������
������ ���� ����������� �������� ��� ICMP �������. ��� ����������
����������� �������������, ����� �� ��������� ��������
—protocol icmp. ��������, ���
��� �������� ICMP ������� ����� ������������� �
����� ��������, ��������� �������� � ����� ��������� �
����� ���������� � ��.

������� 6-7. ICMP ��������

�������� —icmp-type
������ iptables -A INPUT -p icmp
—icmp-type 8
�������� ��� ��������� ICMP ������������ �������
��� ������. �������� �������� ������������ � RFC
792. ����� �������� ������ ���� ICMP �������� ���������
������� iptables —protocol icmp
—help
, ��� ���������� ���������� ���� ICMP. ��� �
�����, ������ ! ����������� ��������,
�������� —icmp-type ! 8.


6.4.3. ����� ��������

����� �������������� ���� ����������, ��� ������ ����
��������� ����, � ������� ����� -m ��� —match. ���, ��������, ���� ��
���������� ������������ �������� state, �� �� ������ ����
������� ��� � ������ �������: -m state ����� �������������
��������. ��������� �� ���� ��������� ���� ��� ��������� �
������ ����������, � ������ ����� �������� �� ������,
������, � ����������� �������, ��� �������� ������
���������. ��� ������� ����� ������ � �������� ����������
����������� ������ � ���, ��� ������ ����� ���������� ����,
� ������ ������������ �������������.


6.4.3.1. �������� Limit

������ ������������ ���� ������ -m limit. ��������� ��������
��� ������, ������������ ������ � ��������� ������
(logging) � �.�. �������� ���� ��������, �� ��� �����
������������� ���������� ����� ������� � ������� �������,
������� �������� ���������� �������. ����� ������������
������ ! ��� ��������, ��������
-m limit ! —limit 5/s. � ����
������ ���������������, ��� ������ ����� ���������
������� ������ ����� ���������� �����������.

����� �������� ���� �������� ����� ����������� ����
��� ��������� ������� � ��������� ����������, �����
������� �������� ������������ ����� ������� �� �������
������� (�.�. �������� «���������»). ��������
«���������» ��� ��� � ���������� ��������
—limit. �������� —limit-burst ������ �����
«����� �������». � ������ ���������� ����
������� —limit 3/minute —limit-burst
5
, ����� ����� ����������� 5 ������� (�� �����
�������� ���������� �������), �������
«����������» � ������ ����������� ����� �����
�������� «������������» �������, �.�.
«������������» ��������. ����� 20 ������
«�������» � ������� ����� ������� (�
������������ � ��������� —limit), ����� ������� ���
������ ����� ������� ��� ���� �����, �� �������
«������������» �������, �.�. ������������
��������.

���������� ��� ���������.

  1. ����������� ������� �������, ����������� ��������
    -m limit —limit 5/second —limit-burst 10. ����
    limit-burst ��������� ����� «�������»
    ������ 10-��. ������ �����, ������� ��������� ���
    ��������� �������, ������������ � ��� �������.

  2. ��������, � ������� 1/1000 �������, �� �������� 10
    �������, ����� � ���������� ������� ������
    «�������» � «�������» �����
    ����������: 1-2-3-4-5-6-7-8-9-10.

  3. ������� �����������. ������ ������, �����������
    ��� ���� ��������������� �������, ������ �� ������
    ������� � ��� «�������» (��� ������ ���
    �����), ������� ��� (������) ������ ������ �� ������
    ������, ���� �� ����� ���� ���������� ����� �� ���,
    ���� ������������ �������� ��-���������.

  4. ������ 1/5 ������� «�������» �
    ������������ ������� ��������� �� 1, � ��� �� ���
    ���, ���� «�������» �� ����� ����������.
    ����� �������, ����� ������ 10-�� �������
    «�������» ������ ����� ������� ��� 5
    �������.

  5. ���� ����� ����������, ��� «�������» �
    «�������» ���������� �� 1 � ������ �����
    ��������� �������.

�� �����������: ����� ������
����� ��� ��������� ��������� limit ���������� �� �����������
������, ���� �������� �������� (������ ����� �
����������� �������) �� �������� ��� ������ � ������� ���
����. ���������� �������� ��� ���������:

  1. ���������� -m limit �������������
    ������� ������ —limit � —limit-burst. ���� �� ��
    ���������� ��� �����, �� ��� ��������� ��������
    ��-���������.

  2. ���� —limit-burst — ���
    ������������ �������� �������� �������, ��� �������
    ����������� �����������.

  3. ���� —limit — ��� ��������, �
    ������� ������� burst limit «�������������
    �����».

�������, ������� ������ ����������� ��
C � ������ ������������ �� ������
����������-�������������.

������� 6-8. ����� ��������
limit

���� —limit
������ iptables -A INPUT -m limit
—limit 3/hour
�������� ��������������� ������� ��������
«������������ �������» �� �������
�������. � �������� ��������� ����������� �����
������� � �����. ����������� ��������� ���������
������� ��������� �������: /second /minute /hour /day. �� ���������
������� �������� 3 ������ � ���, ��� 3/hour. �������������
����� �������� ������� ! � ������ ��������
����������.
���� —limit-burst
������ iptables -A INPUT -m limit
—limit-burst 5
�������� ������������� ������������ ��������
����� burst limit ��� ��������
limit. ��� �����
������������� �� ������� ���� ������� �����,
����������� ��� �������� ������� �������, � ���
���� ������� �������� (���������� ������ —limit) �����������
������� ��� ����������. ��� ���������� �� ���
���, ���� ����� burst limit �� ���������
������������� ��������, ���������������� ������
—limit-burst. �����
����� ������� �������� ���������� ������ ��
���������, ���������� ������ —limit. ��������
��-��������� ����������� ������ 5. ���
������������ ��������� ������ ������� �������� �
������� �������� Limit-match.txt
������� ����� �������� �� ������� ��� ��������
�������� limit, ������ �������
ping-������ � ���������� ����������
�����������.


6.4.3.2. �������� MAC

MAC (Ethernet Media Access Control)
�������� ������������ ��� �������� ��������� MAC-������
������. ���������� -m mac, �� ����������� ����,
������������� ������������ ��������, �� �������� �
������� �� ����� �������� � ������ ����� �������.

Note

������ ���������� ������ ������������ ����
������ -m mac. �������� � ��
���� ������, ��� ������, ����� ������� ���� ����,
����������, ������ �� �������� ���� ��������.

������� 6-9. ����� �������� MAC

���� —mac-source
������ iptables -A INPUT -m mac
—mac-source 00:00:00:00:00:01
�������� MAC ����� �������� ����,
����������� �����. MAC ����� ������
����������� � ����� XX:XX:XX:XX:XX:XX. ��� �
�����, ������ ! ������������ ���
�������� ��������, �������� —mac-source !
00:00:00:00:00:01
, ��� �������� —
«����� � ������ ����, ����� ����, �������
����� MAC ����� 00:00:00:00:00:01» . ����
�������� ����� ����� ������ � �������� PREROUTING, FORWARDINPUT � ����� �����.


6.4.3.3. �������� Mark

�������� mark ������������� �����������
«��������» ������ ����������� �������. Mark — ����������� ����,
������� ���������� ������ � ������� ������ ���� � �������
� ���������� �������. ����� �������������� � �����
������������� �����, ��������, ����������� ������� �
����������. �� ����������� ���� ���������� ������������
����������� ��������� ����� �� ����� � Linux — ���
������������� �������� MARK. ���� mark ������������ �����
����������� ����� ����� � ��������� �� 0 �� 4294967296
��� 32-������ ������.

������� 6-10. ����� ��������
Mark

���� —mark
������ iptables -t mangle -A INPUT -m
mark —mark 1
�������� �������� ���������� ��������
�������, ������� ���� ��������������
«��������». ����� ���������������
��������� MARK, ������� �� �����
������������� ����. ��� ������, ���������� �����
netfilter ����� ����������� ���� mark. ���������, ���
��� ������� ����������� �������� ��������� �����
���� ������ � ������� � ����. ���� mark �������� �����
�����������, ����� ������� ����� ������� �� �����
4294967296 ��������� �����. �����������
������������ ����� � ������. � ������ ������
�������� ����� ��������� �������� �������:
—mark 1/1. ����
����������� �����, �� ����������� ���������� AND
����� � �����.


6.4.3.4. ��������
Multiport

���������� multiport ��������� ��������� �
������ ������� ��������� ������ � ���������� ������.

Note

�� �� ������� ������������ �����������
�������� ������ � ���������� -m multiport (��������
—sport 1024:63353 -m multiport
—dport 21,23,80
) ������������. ��������
������� ����� ������ ����������� iptables.

������� 6-11. ����� ��������
Multiport

���� —source-port
������ iptables -A INPUT -p tcp -m
multiport —source-port
22,53,80,110
�������� ������ ��� �������� ������
��������� ������. � ������� ������� ��������
����� ������� �� 15 ��������� ������. ��������
������ � ������ ������ ���������� ���� �� �����
��������, ������� � ������ �� ���������. ������
���������� ����� �������������� ������ ���������
� ���������� -p tcp ��� -p udp. ������� �������
������������ ��� ����������� ������ ��������
�������� —source-port.
���� —destination-port
������ iptables -A INPUT -p tcp -m
multiport —destination-port
22,53,80,110
�������� ������ ��� �������� ������ �������
������. ������ ������� ���������� ���������
���������� -m multiport
—source-port
.
���� —port
������ iptables -A INPUT -p tcp -m
multiport —port 22,53,80,110
�������� ������ �������� ��������� ���
��������� ��� � �������� ���� ������. ������
���������� ���������� �������� —source-port—destination-port.
�������� �������� �� �� ��� ������ ��������
��������� ����� ����� �����������, �.�. ���� ��
������ -m multiport —port 80,
�� ��� ������ �������� ��������� ������, ������ �
����� 80 �� ���� 80.


6.4.3.5. �������� Owner

���������� owner ������������� ���
�������� «���������» ������. ���������� ������
���������� ���� �������� ��� ������ ������������
������������ iptables. ����������� ������������ ����
�������� ������ � ������� OUTPUT. ����� ����������� ��������
������, ��� �� ����������� ���� ��� ��������� ���������
�������� ���������� � «���������» �� ����.
�������������� ���� ������� ��������, ��� ��� ���������
������� ���������� ���������� «���������» �
���� �������. � ������ ���� ������� ��������� ���������
ICMP responses. ������� �� �������
��������� ���� �������� � ICMP responses �������.

������� 6-12. ����� ��������
Owner

���� —uid-owner
������ iptables -A OUTPUT -m owner
—uid-owner 500
�������� ������������ ��������
«���������» �� User ID (UID).
��������� ���� �������� ����� ��������������, �
�������, ��� ���������� ������ � ��������
��������� �������������.
���� —gid-owner
������ iptables -A OUTPUT -m owner
—gid-owner 0
�������� ������������ ��������
«���������» ������ �� Group ID (GID).
���� —pid-owner
������ iptables -A OUTPUT -m owner
—pid-owner 78
�������� ������������ ��������
«���������» ������ �� Process ID (PID). ����
�������� ���������� ������ � �������������,
��������, ���� �� ����� ��������� ��������
������� �� HTTP ���� ������ ��
��������� ������, �� ��� ����������� ��������
��������� ��������, ������� �������� PID �������� (���� ��
����� ps) � ����� ����������� ��������� PID � �������. ������
������������� �������� ����� ����� � Pid-owner.txt.
���� —sid-owner
������ iptables -A OUTPUT -m owner
—sid-owner 100
�������� ������������ �������� Session ID ������.
�������� SID ����������� ���������
���������� �� «��������», ���,
��������, ��� �������� HTTPD ����� ���� � ��� ��
SID (�������� �����
��������� ����� ������� HTTPD Apache � Roxen).
������ ������������� ����� �������� ����� ����� �
Sid-owner.txt.
���� �������� ����� ��������� �� ������� ���
�������� ������� �������� HTTPD, � � ������
���������� — ������������� «�������»
�������, ����� ���� �������� ���������� �������
OUTPUT � ������ ��
�����.


6.4.3.6. �������� State

�������� state ������������ ��������� �
����� ����������� ���������� � ��������� ��� ��������
���������� � �������� ��������� ����������, ��� ���������
������ � ��������� ����������, ������ ���� ��� �����
���������� ��� ICMPUDP. ������ ���������� ����������
��������� ����, � ������� ����� -m state. ����� ��������
�������� ����������� ��������� ���������� ����������� �
������� �������� �����������
���������
.

������� 6-13. ����� ��������
State

���� —state
������ iptables -A INPUT -m state
—state RELATED,ESTABLISHED
�������� ����������� ������� ���������
���������� (state) �� ����������� ���� �����
��������� 4 ���������: INVALID, ESTABLISHED, NEWRELATED. INVALID �������������,
��� ����� ������ � ����������� ������� ���
����������� �, �������� �������� ������ � ������
��� � ���������. ��������� ESTABLISHED ���������
�� ��, ��� ����� ����������� ��� ��������������
���������� ����� ������� ������ ���� � �����
������������. ������� NEW �������������, ���
����� ��������� ����� ���������� ��� �����
����������� ����������������� ������. � �������,
������� RELATED ��������� �� ��
��� ����� ����������� ��� �������������
����������, �� ��� ���� �� ��������� �����
���������� �������� ���� ����� ������� ��������
������ �� FTP, ��� ������ ���������
ICMP �� ������, �������
������� � ������������ TCP ��� UDP �����������. ������,
��� ������� NEW ��� �� �� �� �����,
��� ������������� ��� SYN � ������� TCP, ����������� �������
����������� ����� ����������, �, ��������� ����
������, ����� ���� ������������ ������ � ������,
����� ��� ������ ���� �� ����������� ���� �������
�����. ����� �������� ��� ��������
��������������� ���� � ����� �������� �����������
���������
.


6.4.3.7. �������� TOS

�������� TOS ������������ ��� ����������
�������� ����� ���� TOS. TOS — Type Of Service
������������ ����� 8-�� �������, ���� � ���������
IP-������. ������ ������ ����������� ����, ������ -m tos.

�� �����������: �����
���������� �������� ���� TOS, ������ �� �� ���������,
��������� ������������ �������� � ������ ���������
��������.

������ ���� ������ ��� ���� ������������� ������.
��������� ������ ���� ����� �������� � ����, ��� �����
����� ��������� ��������������� �� ��� ��� ����� ��
����������� ������ TOS. ������ ��� ���� TOS ����� ���� ��������. � ������
����� ���� ���������� ������ ���� �� ����� ����� ����,
������� ���������� �� ���������. ������ ��� ����������
��� ������� ������:

����������� ��������
������������ � ���������, ����� ����� �������� ������
������ ���� �����������, �.�., ���� ���� �����������, ��
������������� ��� ������ ������ ����� �������� �����
���������� �����. ��������, ���� ���� ����� �����
�������������� ������ � ����������� �������, ��
������������ ����� ������ ����� �����������
�����������.

������������ ����������
�����������
���������, ��� ����� ������ ����
����������� ����� ����� � ������������ ����������
������������. �������� ����������� ������, �������
������� ��������� ����� ������� ����������
�����������.

������������ ����������
���������� ����������� �������� ������� �� ���������
������������� ��������� �������� ������. �������� �����
������� PPP � SLIP ����������, ������� �� �����
���������� ��������, � �������, ����� X.25, �������,
������� ��������� ����� ������������� ����������� �������
� ���������� �����������.

����������� ������� �����������
� �������, ����� ����� �������������� ������� (� ������
������) �� �������� ������. ��������, ��� �������� �����
����� (�� ������ ���������) ������ ������������ ������
����� ��������� �������, ��� ������ ���������������
������. ��������� ������� ���� ������ ����� �������� �
����, ��� ����� ������ �� ����� «��������»
��������.

������� ������ � ������
�������� ��� ���� ���� TOS ��������. ������������� ������
������ ��������� �������� �� ���������� ����������.

������� 6-14. ����� ��������
TOS

���� —tos
������ iptables -A INPUT -p tcp -m tos
—tos 0x16
�������� ������ �������� ������������ ���
�������� ������������� ����� TOS, ������� �����������
����. ��� ������� ���� ������������ ��� ����
�������������, �� ������ ����� ���� ������������
� ����� «����������» ������� ���
������������� � iproute2 � ��������������
������������� � linux. � �������� ���������
�������� ����� ���� �������� ���������� ���
����������������� �����, ��� �������������
�������� ����, ��������� � �� �������� ��������
�� ������ �������� �������� ������� iptables -m tos -h.
���� ���������� ��������� � �� ��������. Minimize-Delay 16
(0x10) (����������� ��������), Maximize-Throughput 8
(0x08) (������������ ����������
�����������), Maximize-Reliability 4
(0x04) (������������ ����������), Minimize-Cost 2
(0x02) (����������� �������), Normal-Service 0
(0x00) (������� ������)


6.4.3.8. �������� TTL

TTL (Time To Live) ��������
�������� ����� � IP ���������. ��� ����������� ����������
��������������, ��� ����� ����������� �� 1. ���� �����
���������� ������ ����, �� ����������� ������ �����
�������� ICMP ��������� ���� 11 � ����� 0
(TTL equals 0 during transit) ���
� ����� 1 (TTL equals 0 during reassembly) .
��� ������������� ����� �������� ���������� ����
��������� ������ ������ -m ttl.

�� �����������: �����
������������ ��������� �������������� �������������
������ � �����������������, �� ������� ���� ��� iptables
1.2.6a, � ������� ���������� � ���� ����, ���������� ���
��������� �������� �������� ���� TTL, ��� -m ttl —ttl-eq �����, -m ttl —ttl-lt �����-m ttl —ttl-gt �����.
���������� ���� ��������� ������� ��� �� �� ����������.
��� �� �����, � ��� ���� ������� �������
���������:

������� 6-15. ����� ��������
TTL

���� —ttl
������ iptables -A OUTPUT -m ttl —ttl
60
�������� ���������� �������� ���� TTL �� ��������� ���������
��������. ������ �������� ����� ���� �����������
��� ������� ��������� ����, ��������: ���
�������, ����� ����� ���� ������ ��������� ����
�� ����� ������������ � ������� � ���������, ���
��� ������ «�������» � ��. ������,
������� ���������� ����� ���� ��������������
������ ����� ���������. ��� ���� ������:
������������� ����� �������� ����� ����
���������� �� ����� ����� � ��������������
����������� ����� TCP/IP ��� � �������� �
������������ ��.


6.4.4. �������� «������»
(Unclean match)

�������� unclean �� ����� ��������������
������ � ��� ��� ������������� ���������� ���� ���������
������. ������ ���������, ������ ������ ��������� ��� ��
������ ���������� � ������� � ��������� ��������� �����
�������� �����������. ������ �������� ������������ ���
���������� �������, ������� ����� ����������� � ���������
�����������, ��� ����� ���� ������ � ������������
���������� ��� � �������� ����������� ������ � ��., ������
������������� ���� �������� ����� �������� � ������� �
������ ����������� ����������.


6.5. �������� � ��������

�������� � �������� �������� �������, ��� ����������
���������, ���� ����� ������������ ��������� ��������. ����
����� ������������� �������� ACCEPTDROP. ������, ������� ������
���������� ������� ���������.

�������� ��������� � �������� �������� ����� ��� �� ��� �
�������� ��������, �.�. �������� ���� -j � ����������� �������� �������
������, �� ������� ����������� �������. �� ��������
������������� ��� �����������, ������ — �������, �� �������
����������� �������, ������ ���������� � ��� �� �������, ���
� �������, �� ������� ���� ������� �����������, ������ —
������� , ���������� ����� �������� ������ ���� ������� ��
���� ��� �� ��� ����� ����������� ��������. ��������,
�������� ������� tcp_packets � ������� filter �
������� �������

iptables -N tcp_packets
   

������ �� ����� ��������� �������� �� ��� �������
�������:

iptables -A INPUT -p tcp -j tcp_packets
   

�.�. �������� ����� ��������� tcp, iptables ����������
������� �� ������� tcp_packets � ��������� ��������
������ �� ���� �������. ���� ����� ������ ����� ������� �� ��
����� ��������� � ���������� ������� (� ����� ������ ���
������� INPUT) � �������� ������
����������� � �������, ���������� �� ��������, ���������
�������. ���� � ������ �� ��������� ������� ����� ���������
�������� ACCEPT, �� ������������� �����
����� ��������� �������� � � ���������� ������� � ��� ��
����� ���������� �������� �� ���������� ��������. ������
����� ������ �� ������ �������� � ������ ��������.
�������������� ���������� � ������� ����������� ������� �
������ �� ������� �������� � ����� ������� ����������� ������ �
�������
.

�������� — ��� ���������������� �������, �����������
��������, ������� ���������� ���������, ���� ����� ������ �
�������� ���������. ��������, ����� ��������� ��������
DROP ��� ACCEPT � ������, � ����������� ��
����� ����. ���������� � ��� ������ ��������, �������
����������� ���� � ���� �������. � ���������� ����������
����� ��������, ����� ���������� ���� ����������� �� �������,
�������� DROPACCEPT, � ���������� ������, �����
���������� ����� ��������, ���������� ��������, ��������,
LOG, � ���������� ������ �������
���� ��������������, �������� DNATSNAT, TTLTOS, �� ��� �� ����������
����������� �� �������.


6.5.1. �������� ACCEPT

������ �������� �� ����� �������������� ������. ���� ���
������� ����������� �������� ACCEPT, �� ����� ����������
�������� �� ������� (� ���� ��������� ��������, ����
������� ������� ���� ���������) � ��������� �������� (��
���� ������������), ��� �� �����, ����� ��������� ��������
�� �������� � ������ �������� � ����� ���� ��������� ���.
�������� �������� � ������� ����� -j ACCEPT.


6.5.2. �������� DNAT

DNAT (Destination Network Address
Translation) ������������ ��� �������������� ������ �����
���������� � IP ��������� ������. ���� ����� ��������� ���
�������� �������, ������������ DNAT, �� ���� �����, � ���
����������� ������ �� ����� �� ������, ����� �����������
�������������� ������ ���������� � �������� �� ���������
����������, ���� ��� ����. ������ �������� �����, �
�������, ������� �������������� ��� �������������� �������
� ������ web-�������, ������������ � ��������� ����, � ��
�������� ��������� IP ������. ��� ����� �� ������� �������,
������� ������������� ������, ������ �� HTTP ���� ����������� � ��������
DNAT ��������� �� �� ���������
����� web-�������. ��� ����� �������� ��� �� ����� �������
�������� �������, ����� ����� ������ ���������� ��� �������
������ ������ ����� ������������� ��������� �������.

�������� DNAT ����� ����������� ������ �
�������� PREROUTINGOUTPUT ������� nat, � ��
��������� ���-��������. ����� ���������, ��� ���������
����������, ����������� DNAT �� ������ ���������� ��
������ �������, ����� PREROUTINGOUTPUT.

������� 6-16. �������� DNAT

���� —to-destination
������ iptables -t nat -A PREROUTING -p
tcp -d 15.45.23.67 —dport 80 -j DNAT
—to-destination
192.168.1.1-192.168.1.10
�������� ���� —to-destination
���������, ����� IP ����� ������ ���� ���������� �
�������� ������ ����� ����������. � ����
����������� ������� �� ���� �������, ��������� ��
����� 15.45.23.67, ����� ���������� ����� �������
�� ���� �� ��������� �� 192.168.1.1 ��
192.168.1.10. ��� ��� ����������� ����, ��� ������
�� ������ ������ ����� ������������ �� ���� � ���
�� �����, � ��� ������� ������ ������ �����
���������� ���� �� ������� � ��������� ���������
��������� �������. ����� ����� ����������
������������ IP �����. ����� ������������� �������
���� ��� �������� ������, �� ������� (�������)
����� ������������� �������. ��� ����� ����� ip
������ ����� ��������� ������� ����, ��������
—to-destination
192.168.1.1:80
, � �������� ���������
������ �������� ���: —to-destination
192.168.1.1:80-100
. ��� �� ������ ������,
��������� �������� DNATSNAT �� ������ ����. ��
���������, ��� �������� ������ ����������� ������
��� ������ � ���������� TCP ��� UDP, ��� �������
����� —protocol
��������.

�������� DNAT ���������� ������ �
������������� � ������� ��������������� ���������.
���������� ������� ������. � ��� ���� WEB ������ � �� �����
��������� ������ � ���� �� ��������. �� ����� ������ ����
�������� IP �����, � WEB-������ ���������� � ���������
����. �������� IP ����� $INET_IP �������� �����������,
HTTP ������ ����� ��������� ����� $HTTP_IP �, ������� ����������
����� ��������� ����� $LAN_IP. ��� ������ �������
������� ������� � ������� PREROUTING ������� nat:

iptables -t nat -A PREROUTING --dst $INET_IP -p tcp --dport 80 -j DNAT \
--to-destination $HTTP_IP
   

� ������������ � ���� ��������, ��� ������, �����������
�� 80-� ���� ������ $INET_IP ���������������� �� ���
���������� WEB-������. ���� ������ ���������� � WEB-�������
�� ��������, �� ��� ����� �������� ���������. �� ��� ��
����������, ���� ����������� ����������� � ��� �� ���������
����? ���������� ������ �� �����������. ������� ���������
��� ���������������� ������, ������ �� �������� �� ���
WEB-������. ��� �������� ��������� ������ ����� ������� �
�������� ������ $EXT_BOX.

  1. ����� �������� ���������� ���� � ������� $EXT_BOX � ������������ ��
    $INET_IP

  2. ����� �������� �� ��� ����������.

  3. ����������, � ������������ � ���������������
    ��������, ��������� ����� ���������� � �������� ���
    ������, � ������ �������.

  4. ����� ���������� �� $HTTP_IP.

  5. ����� ��������� �� HTTP ������ � ������ ��������
    ����� ����� ����������, ���� � ������� ������������� ��
    ��������� ��� ���� ��� $EXT_BOX. ��� �������, ��
    ����������� ������ ��-��������� ��� HTTP �������.

  6. ���������� ���������� �������� ����������� ������ �
    ������, ������ ��� �������� ���, ��� ����� �� ����� ���
    ����������� �� �����������.

  7. ����� ���������� ������� $EXT_BOX.

� ������ ���������, ��� ����������, ���� ������
���������� � ����, �������������� � ��� �� ��������� ����.
��� �������� ��������� ������ ����� ������� � ���������
���� ������ $LAN_BOX.

  1. ����� �������� $LAN_BOX.

  2. ��������� �� ����������.

  3. ������������ ����������� ������ ����������, ������
    ����� ����������� �� �����������, �.�. �������� �����
    �������� � ������ ��� ���������.

  4. ����� �������� ���������� � ������������ �� HTTP
    ������.

  5. HTTP ������, �������� � ��������
    ������, ������������, ��� ������ ��������� � ���������
    ���� (��������� ����� ������� �������� ������������ IP
    �����, ������� ������ ����������� � ����� ����������) �
    ������� ���������� ����� ��������������� �� $LAN_BOX.

  6. ����� ��������� �� $LAN_BOX. ������
    «��������», ��������� ����� ������ �� � ����
    ����, �� ������� ����������� ������. ������� ������
    «����������» ����� ������ � ���������� �����
    «���������» �����.

�������� �������� �������� ������ � ������� SNAT. ���� ���������� �������,
������� ��������� ��� �������. ��� ������� ��������� HTTP
������ ���������� ������ �� ��� ����������, ������� �����
����� �������� �������.

iptables -t nat -A POSTROUTING -p tcp --dst $HTTP_IP --dport 80 -j SNAT \
--to-source $LAN_IP
   

���������, ������� POSTROUTING �������������� �����
��������� � � ����� ������� ����� ��� ������ ���������
�������������� DNAT, ������� �������� ��������
�� ���� ������ ���������� $HTTP_IP.

���� �� �������, ��� �� ���� ����� ������������, �� ��
����������! ���������� ���� ��������, ����� � ��������
������� ��������� ��� ����������. �����, � ���������,
������ ����� ������������ �� ��������� ���� � ������� 80
������ �����������, � �� �� $HTTP_IP. ����� ��������� � ���
��������, ������� �������:

iptables -t nat -A OUTPUT --dst $INET_IP -p tcp --dport 80 -j DNAT \
--to-destination $HTTP_IP
   

������ ������� �������, � �������� � ������ WEB-�������,
��� �� ������ ���������.

Note

������ ������ ������, ��� ��� �������
������������� ������ ���� ��� ���������� ���������
��������� �������. � ���������� � ���� �������� ���
����� ������������� �������� �������������� �������
��� ������� FORWARD ������� filter. ��
�������� ��� ����, ��� ������ ��� ������ �������
PREROUTING � ������� ��
������ ���������� ��� �������� ��������� DNAT.


6.5.3. �������� DROP

������ �������� ������ «����������» ����� �
iptables «��������» � ��� �������������.
«����������» ������ ���������� ���� ��������
���������, �.�. ��� �� ���������� � ������ �������, ��� ���
���������� � ������ � ��������� ACCEPT. ������� �������, ���
������ �������� ����� ����� ���������� �����������,
��������� ����� ��������� ���������� «�������»
������ ��� �� ������� �������, ��� � �� ������� �������,
��������� �������� ������ ����� ������������� ��������
REJECT �������� ��� ������ ��
������������ ������.


6.5.4. �������� LOG

LOG — ��������, ������� ������
��� �������������� ��������� ������� � �������. � ������
����� ���������� ��������� IP ������� � ������ ������������
��� ����������. ���������� �� ������� ����� ���� �����
��������� � ������� dmesg ��� syslogd ���� � ������� ������
��������. ������������ �������� ��� ������� ����� ������.
������� ���� �� �� ������ ������� ������ ������ ��������
DROP ������������ ��������
LOG, ����� �� ����� ���������,
��� ��� ���������� �������� ����������. �������� ����
�������� ��� �� �� �������� ULOG, ������� ���������
������������ ��� ������ �������������, ��������� ���������
��������� ������ ������������� ���������� �� � ���������
������, � � ���� ������ MySQL � �.�..

Note

�������� �������� — ���� � ��� ������� ��������
� ������� � ��������� ������, �� ��� �������� ��
iptables ��� netfilter, � syslogd. �� �����������
�� ���������������� syslogd ����������� � man syslog.conf.

�������� LOG ����� ���� ������, �������
����������� ����.

������� 6-17. ����� �������� LOG

���� —log-level
������ iptables -A FORWARD -p tcp -j LOG
—log-level debug
�������� ������������ ��� ������� ������
�������������� (log level). ������ ������ �������
�� ������� � ����������� (man) �� syslog.conf.
������, ����� ������ ��������� ������: debug, info, notice, warning, warn, err, error, crit, alert, emergpanic. �������� ����� error �������� �� �� �����,
��� � err, warnwarningpanicemerg. �����: � ���������
���� ����� ���� �� ������� ������������ error, warnpanic. ��������� ����������
�������� � ��� ��� ����� ���������� ��������� �
������. ��� ��������� ��������� � ������ ����������
����. ���� �� ���������� ������ kern.=info
/var/log/iptables
� ����� syslog.conf, ��
��� ���� ��������� �� iptables, ������������
������� info, ����� ���������� �
���� /var/log/iptables ������, � ���� ���� �������
� ������ ���������, ����������� �� ������
���������, ������� ���������� ������� info. �� ��������������
����������� �� syslog � syslog.conf � ����������
���������� � manpages � HOWTO.
���� —log-prefix
������ iptables -A INPUT -p tcp -j LOG
—log-prefix «INPUT
packets»
�������� ���� ������ ����� (�������), �������
����� ������������ ��� ��������� iptables. ��������� ��
����������� ��������� ����� ����� ����� �����, �
�������, � ������� grep. ������� �����
��������� �� 29 ��������, ������� � �������.
���� —log-tcp-sequence
������ iptables -A INPUT -p tcp -j LOG
—log-tcp-sequence
�������� ���� ���� ��������� �������� � ������
����� TCP Sequence ������. �����
TCP Sequence ��������������
������ ����� � ������ � ���������� �������
«������» ������. ���� ���� ������������
������ ��� ������������ �������, ���� ���������
������ ��������� ������ «�� ������» ����
�������������. ��� � ����� ������ ������,
���������� ��������� �� iptables.
���� —log-tcp-options
������ iptables -A FORWARD -p tcp -j LOG
—log-tcp-options
�������� ���� ���� ��������� �������� �
��������� ������ ��������� �������� �� ���������
TCP ������. ����� ����������� ����� ���� �������
��� �������. ���� ���� �� ����� ��������������
����������, ��� � ����������� ������ ��������
LOG.
���� —log-ip-options
������ iptables -A FORWARD -p tcp -j LOG
—log-ip-options
�������� ���� ���� ��������� �������� �
��������� ������ ��������� �������� �� ��������� IP
������. �� ������ ���� � ������ —log-tcp-options, ��
�������� ������ � IP ����������.


6.5.5. �������� MARK

������������ ��� ��������� ����� ��� ������������
�������. ��� �������� ����� ����������� ������ � ��������
������� mangle. ��������� ����� ������
������������ ��� ���� ������������� ������� �� ���������
���������, ��� ����������� ������� � �.�.. ��
�������������� ����������� �� ������ ���������� � Linux Advanced Routing and Traffic
Control HOW-TO
. �� ���������, ���
«�����» ������ ���������� ������ � ������ �������
���� ����� �� ������� ����������, �.�. ����� �� ����������
�� ����. ���� ���������� ���-�� �������� ������, �����
������������ ���������� �� ������ ������, �� ������
����������� �������������� ������ ���� TOS.

������� 6-18. ����� �������� MARK

���� —set-mark
������ iptables -t mangle -A PREROUTING
-p tcp —dport 22 -j MARK —set-mark
2
�������� ���� —set-mark �������������
����� �� �����. ����� ����� —set-mark ������
��������� ����� ����������� �����.


6.5.6. ��������
MASQUERADE

����������� (MASQUERADE) � ������ �����
������������ �� �� �����, ��� � SNAT ������ �� ����� �����
—to-source. �������� ���� ��,
��� ����������� ����� ��������, ��������, � dialup
������������ ��� DHCP, �.�. � ��� �������, ����� IP �����
������������� ���������� �����������. ���� � ��� �������
������������ �����������, �� ����� ������������
�����������, ���� �� � ��� ����������� IP �����������, ��
��������� ������ ������� ����� ������������� ��������
SNAT.

����������� ������������� ��������� IP ������ ��
��������� �������� ����������, ������ ������� ��� ��������,
��� ��� �������� � ������� ����� —to-source � �������� SNAT. �������� MASQUERADE ����� ������� ��������
— «��������» ���������� ��� ��������� ��������
����������. � ������ �� SNAT, � ���� ��������, � �������
������������� �������� ������ � ���������� �����������, �
��� ������ ����� ����������� �� �����, �������� ������
������. ������ «������������» ������ � ���, ���
��� ��������� �������� ���������� � ������������ IP
�������, ���� ����������� �� ��������� ������� ��������
������ IP �����, �� � ���� ������ ����� ���������� ���
����� ����� ��������, � ���� �� ����� �������
�������������� ����������.

��� �� ��� ������, �������� MASQUERADE ����� ����
������������ ������ SNAT, ���� ���� �� ������
���������� IP �����, ������, �������� �� �������������
�����, ����������� �� ������� ������� ���������������� �
���� ������, ��������� �� ���� ������� �������� ��
�������.

�������� MASQUERADE ����������� ���������
������ � ������� POSTROUTING ������� nat, ��� �� ���
� �������� SNAT. MASQUERADE ����� ����,
����������� ����, ������������� �������� �������������.

������� 6-19. �������� MASQUERADE

���� —to-ports
������ iptables -t nat -A POSTROUTING -p
TCP -j MASQUERADE —to-ports
1024-31000
�������� ���� —to-ports ������������
��� �������� ����� ��������� ��� ��������� ������
���������� ������. ����� ������� ���� ����,
��������: —to-ports 1025, ���
�������� ������ ��� �����: —to-ports 1024-3000.
���� ���� ����� ������������ ������ � ��������, ���
�������� �������� ����� �������� �� �������� TCP
��� UDP � ������� ����� —protocol.


6.5.7. �������� MIRROR

�������� MIRROR ����� �������������� ����
������ ��� ������������� � � ���������������� �����,
��������� ��� �������� ����� �������� �
«������������» ������ � � ���������� �
«������ �� ������������». � ���������� ��������
MIRROR � ������, ���� source �
destination �������� ������� (invert the source and
destination fields) � ����� ������������ � ����.
������������� ���� ������� ����� ����� ������ ��������
���������, ��������, �� ������� �������� ������� ���������,
��� ����� ������ ���������� �������� «��������»
���� ����������� ���������!

������ �������� ����������� ������������ ������ �
�������� INPUT, FORWARDPREROUTING, � � ��������, ����������
�� ���� ����. ������, ������������ � ���� ��������� MIRROR ������ �� ������������
����������, ����������� ��� NAT, ������� ��� �����
«������������» � ������ �������������. ������ ���
�� ��������, ��� ������� � ���� ��������� ���. �������, �
�������, ����������, ��� �� �����, ������������ ��������
MIRROR ����������� �����, �
TTL ������ 255, �� ���� �� �����
���� � ����� ��������� ��� ��������
«��������������» �������. �����
«����������» �� ���� �� ����, � ��������� �����
«����������» � «������������» ������ 1
��� (hop) �� ����� ����� ������� ���� � ������� 255 ���.
������� ��� �������, ����, ��� �������� ������ 1500 ����,
�� �������� �� 380 ����� �������!


6.5.8. �������� QUEUE

�������� QUEUE ������ ����� � ������� ��
��������� ����������������� ��������. ��� ����� ����
������������ ��� ���� �����, ������������� ���
�������������� ���������� �������.

�� �����������: ����� �����
���������� ���������� � ���, ��� ���������� ������ ����
������ ������� �� ����� ��������� � ��., �������, ��
��������� ������, ������� ����� �������� �� http://antonio.mccinet.ru/protection/iptables_howto.html
� �������� ������� ����������� aka virii5,
eugene@kriljon.ru

«…��� ���� ����� ��� ���� ����
�������, ���������� ��� ��� ����������:

  1. «queue handler» —
    ���������� �������, ������� ��������� ������ ��
    �������� ������� ����� ����� � ����������������
    �����������; �

  2. ���������������� ���������� �������
    ����� ��������, �������� ������������, � ������ ������
    �������.

����������� ���������� ������� ��� IPv4 —
������ ip-queue, ������� ���������������� � ����� � �������
��� �����������������. ���� ��� ������, ��� �����
������������ iptables ��� �������� ������� �
���������������� ����������:

# modprobe iptable_filter
# modprobe ip_queue
# iptables -A OUTPUT -p icmp -j QUEUE

� ���� ��������, ��������� ��������
������ ICMP ���� (�����, ��� ��������� ������ ��� ������
������� ping) �������� � ������ ip_queue, ������� �����
�������� �������� �� � ���������������� ����������. ���� ��
���� �� ����� ���������� �� �������, ������ ������������.
����� �������� ���������������� ��������� ���������
�������, ����������� libipq API. ��� ���������������� �
������� iptables. ������� ����� ����� � testsuite tools
(�������� redirect.c) �� CVS. ������ ip_queue �����
��������� � �������: /proc/net/ip_queue ������������ ������
������� (�� ����, ����� ������� ������������ �
���������������� ���������� ��� ������������� ���������)
����� �������������� � �������:
/proc/sys/net/ipv4/ip_queue_maxlen �� ��������� —
������������ ������ ������� ����� 1024. ��� ������ ����
������ �����������, ����� ������ ����� ������������, ����
������� �� ��������� ���� ������� �������. �������
���������, ����� ��� TCP �������������� ���������� ������
��� ��������������� ������ ��������, � ������� � ����
����������� (��������� � �����, ����� ����� ������ ��������
������ ��������� ��������, ����. �������.). ������, �����
������������� ���������� ���� �������������������, �����
���������� ����������� ����� ������� � ������ ����������
������, ���� �� ��������� ������� �������
����…»


6.5.9. �������� REDIRECT

��������� ��������������� ������� � ������� �� ������
���� ��� �� ����� ������. � �������, ����� ������,
����������� �� HTTP ���� ������������� �� ���� HTTP proxy.
�������� REDIRECT ����� ������ ���
���������� «�����������» �������������
(transparent proxying), ����� ������ � ��������� ���� ����
�� ����������� � ������������� ������.

REDIRECT ����� ��������������
������ � �������� PREROUTINGOUTPUT ������� nat. � ������� �� ���
�������� ����� ��������� � �����������, ���������� �
�������������. ��� �������� REDIRECT ������������ ������ ����
����.

������� 6-20. �������� REDIRECT

���� —to-ports
������ iptables -t nat -A PREROUTING -p
tcp —dport 80 -j REDIRECT —to-ports
8080
�������� ���� —to-ports ����������
���� ��� �������� ������ ����������. ��� ��������
����� —to-ports,
��������������� �� ����������, �.�. ����� ���� ��
��� ����, ���� � ��� ��������. � �������,
����������� ����, —to-ports 8080 ������
���� ���� ����������. ���� ����� ������� ��������
������, �� �� ������ �������� ����� ��������
—to-ports 8080-8090.
���� ���� ����� ������������ ������ � ��������, ���
�������� �������� ����� �������� �� �������� TCP
��� UDP � ������� ����� —protocol.


6.5.10. �������� REJECT

REJECT ������������, ��� �������,
� ��� �� ����� ���������, ��� � DROP, �� � ������� �� DROP, ������� REJECT ������ ��������� �� ������
�� ����, ���������� �����. �������� REJECT �� ����������� ���� �����
�������������� ������ � �������� INPUT, FORWARDOUTPUT (� �� ��������� � ���
��������). ���� ���������� ������ ������������ ����,
����������� ���������� ������� REJECT.

������� 6-21. �������� REJECT

���� —reject-with
������ iptables -A FORWARD -p TCP —dport
22 -j REJECT —reject-with tcp-reset
�������� ���������, ����� ��������� ����������
�������� � �����, ���� ����� ������ � ��������
���������. ��� ���������� �������� REJECT � ������, �������
�� ����-����������� ����� ������� ��������� �����,
� ����� ����� ����� «�������».
����������� ������������ ��������� ���� �������:
icmp-net-unreachable,
icmp-host-unreachable,
icmp-port-unreachable,
icmp-proto-unreachable, icmp-net-prohibited �
icmp-host-prohibited.
��-��������� ���������� ��������� port-unreachable. ���
������������� ���� ������� �������� ICMP error messages.
�������������� ���������� �� ����� ICMP ���������
�� ������ �������� � ���������� ���� ICMP. �
���������� ������ ��� ���� ��� ������ — tcp-reset, �������
������������ ������ ��� ��������� TCP. ���� �������
�������� tcp-reset, �� ��������
REJECT �������� � �����
����� TCP RST, ������ TCP RST ������������ ���
�������� TCP ����������. �� ��������������
����������� ����������� � RFC 793 — Transmission Control
Protocol
. (������ ����� ICMP ������� � ��
������� �� ������� �������� ����� ������� iptables -j REJECT -h
����. �����.)
.


6.5.11. �������� RETURN

�������� RETURN ���������� �������� ������
�� ������� ������� ������ � ���������� ������� � ����������
�������, ���� ������� ������� ���� ���������, ���, ����
������� ������� ����� �� ����� ������� ������ (�������� INPUT), �� � ������ ����� ���������
�������� ��-���������. ������, � �������� ��������
��-��������� ��������� �������� ACCEPT ��� DROP .

��� �������, ��������, ��� ����� ���� �� ������� INPUT � ��������� �������, �������
���������� ������� �� ��������� ������� — —jump EXAMPLE_CHAIN. �����, �
������� EXAMPLE_CHAIN ����� ��������� �������, �������
��������� �������� —jump RETURN. ����� ����������
������� ������ � ������� INPUT. ������ ������, ����� �����
��������� �������, ������� ��������� �������� —jump RETURN � ������� INPUT. ����� � ������ �����
��������� �������� ��-��������� ������� INPUT.


6.5.12. �������� SNAT

SNAT ������������ ���
�������������� ������� ������� (Source Network Address
Translation), �.�. ��������� ���������� IP ������ � IP
��������� ������. ��������, ��� �������� ����� ������������
��� �������������� ������ � �������� ������ ����������� ��
��������� ����, ���� ���� ���� ���������� IP �����. ���
�����. ���������� �������� ��������� ������� (forwarding) �
���� � ����� ������� �������, ������� ����� �������������
��������� IP ������ ����� ��������� ���� � �������� �������
�����. � ����������, ������� ��� ������ �� ����� ����� �
����� ��������� ����, �� ����� �������, ��� ������� ������
� ������ �����������.

SNAT ����������� ��������� ������
� ������� nat, � ������� POSTROUTING. ������� �������, ������
����� ����������� �������������� ��������� �������. ����
������ ����� � ���������� ��������� ��������������
���������� ������, �� ��� ����������� ������, �� ����� ��
����������, ����� ������������� ������������� � �� ������
����� ��� ������� ������.

������� 6-22. �������� SNAT

���� —to-source
������ iptables -t nat -A POSTROUTING -p
tcp -o eth0 -j SNAT —to-source
194.236.50.155-194.236.50.160:1024-32000
�������� ���� —to-source ������������
��� �������� ������, ������������� ������. ���
������, �� ���������� IP �����, ������� �����
���������� � ��������� ������ � ��������
����������. ���� �� ����������� ����������������
�������� ����� ����������� �������������, �� �����
������� �������� �������, ��� ��������� � ��������
������ ��������� ����������� �������, ��������:
194.236.50.155-194.236.50.160. �����, ���������� IP
����� ����� ���������� �� ��������� ���������
������� ��� ������� ������ ������. �������������
����� ������� �������� ������, ������� �����
�������������� ������ ��� ���� SNAT. ��� ��������� �����
����� ����� ����� ����������������� � ��������
��������. iptables ���������, ��-�����������,
�������� ���������������� ������, ������ �� ������
��� ��������, � ����� ������������ ����������������
. ���� �������� ������ �� �����, �� �������� �����
���� 512 ��������������� � ��������� 0-511, ����� �
��������� 512-1023 ��������������� � ���������
512-1023, �, ������� ����� �� ��������� 1024-65535
��������������� � ��������� 1024-65535. ���
�������� ������ ����������, �� ��� �� ������������
����������������.


6.5.13. �������� TOS

������� TOS ������������ ��� ���������
����� � ���� Type of Service IP ���������. ����
TOS �������� 8 ���, ������� ������������ ��� �������������
�������. ��� ���� �� ���������� �����, ������������ iproute2. ��� �� ����� �������,
��� ������ ���� ����� �������������� ����������
���������������� � ����� ������ �������� �������� ������.
��� ��� ����������� ����, ��� ����, � ������� �� MARK, ��������� ���� �������� ���
�������� �� ����, � ������� ����� �������������� ���� ���
������������� ������. �� ����������� ����, �����������
��������������� � ��������� ����� �� ������������ ��� ����,
������ ���� � �����, ������� ������� �� ����. ���� ��
����������� ��� ���� � ����� ������, �� ��������
�������������� ����� ������� �������� ������� ��� ������
��������, �������, ����� ����� ������������ ��� ���� ���
����� ���� ������ � �������� ����� WAN ��� LAN.

Caution

�������� TOS ������������ ������
���������������� �������� �������� � ���������,
������� �� ������ ����� � linux/ip.h. ���� ���
������������� ���������� ������������� ������������
�������� � ���� TOS, �� ����� ���������������
«��������» FTOS � ����� Paksecured Linux Kernel
patches
, ��������������� Matthew G. Marsh.
������, ������ ������ ��������� � ����
«��������». �� ������� ������������
������������� �������� TOS ����� ��� � ���������
���������.

Note

������ �������� ����������� ��������� ������ �
�������� ������� mangle.

Note

� ��������� ������ ������� iptables (1.2.2 �
����) ��� �������� ����������� � ������� (��
������������ ����������� ����� ������), � ��� �����
� ��������� ��������� ������ � � ���������� �����
���������� ����������.

������� TOS ����� ������ ���� ����,
������� ������ ����.

������� 6-23. �������� TOS

���� —set-tos
������ iptables -t mangle -A PREROUTING
-p TCP —dport 22 -j TOS —set-tos
0x10
�������� ���� —set-tos ����������
�������� �������� � ���������� ���
����������������� ����. ��������� ���� TOS ��������
8-������, �� �� ������ ������� ����� � ��������� ��
0 �� 255 (0x00 — 0xFF). ������, �����������
�������� ����� ���� ����� �� ������������. ������
��������, ��� � ������� ����������� TCP/IP ��������
�������� ����� ���� ��������, �������, ��-���������
������, ����� ������������ �������������
�����������: Minimize-Delay (16 ���
0x10), Maximize-Throughput (8
��� 0x08), Maximize-Reliability
(4 ��� 0x04), Minimize-Cost (2 ���
0x02) ��� Normal-Service (0 ���
0x00). ��-��������� ����������� ������� �����
������� Normal-Service, ��� 0.
������ �������� �� ������� ��������, ��������
������� iptables -j TOS -h.


6.5.14. �������� TTL

�������� TTL ������������ ��� ���������
����������� ���� Time To Live � IP ���������. ���� ��
��������� ���������� ����� �������� — ��� �������������
�������� ���� Time To Live �� ���� ��������� ������� � ����
� �� �� ��������. ��� ���� ���?! ���� ��������� ����������,
������� ����� �� �����, ����� ����� ������������ ����������
��������� �����������, ���� �� �������� ������������� ��
��� ������ ���� � �� �� �������� TTL, �� ��� ����� ��
������ ���������� ������ �� ��������� ����������� ����, ���
����������� � ��������� ����������� �����������
������������. ��� ������� ����� �������� ����� TTL = 64,
������� �������� ����������� ��� ���� Linux.

�� �������������� ����������� �� ��������� ��������
��-��������� ����������� � ip-sysctl.txt, �������
�� ������� � ���������� ������ �� ������
�������
.

�������� TTL ����� ��������� ������ �
������� mangle � ����� ������. ��� ������� ��������
������������� 3 �����, ����������� ����.

������� 6-24. �������� TTL

���� —ttl-set
������ iptables -t mangle -A PREROUTING
-i eth0 -j TTL —ttl-set 64
�������� ������������� ���� TTL � ��������
��������. ����������� ��������� �������� ����� 64.
��� �� ������� �����, �� � �� ������� ���� ��
��������� ������� ������� ��������, ��� ����� �����
���������� ����������� ��� ����� ����. �����������
����, ��� ����� «�������������» �����
����� ����������� ������������������� ���������,
�����, ��� ������� ��������� TTL, ���� ����
«��������» ������������ ���� ����������
����������� ������.
���� —ttl-dec
������ iptables -t mangle -A PREROUTING
-i eth0 -j TTL —ttl-dec 1
�������� ��������� �������� ���� TTL ��
�������� �����. ��������, ����� �������� �����
����� �������� TTL ������ 53 � �� ��������� �������
—ttl-dec 3, ����� �����
������� ��� ���� � ����� TTL ������ 49. ��
���������, ��� ������� ��� ������������� ��������
�������� TTL �� 1, �������, ���������� �� ��������
53 — 3 — 1 = 49.
���� —ttl-inc
������ iptables -t mangle -A PREROUTING
-i eth0 -j TTL —ttl-inc 1
�������� ����������� �������� ���� TTL ��
�������� �����. ������� ���������� ������, ����� �
��� ��������� ����� � TTL = 53, �����, �����
���������� ������� —ttl-inc 4, �� ������ �
������ �����, ����� ����� ����� TTL = 56, ��
��������� �� �������������� ���������� ���� TTL
������� ����� ����, �.�. ���������� �� ��������
��������� 53 + 4 — 1 = 56. ���������� ���� TTL
����� �������������� ��� ����, ����� ������� ���
���������� ����� «��������» ���
�������������� (traceroutes). ��������� �����������
����� �� ������ ���������� ��� ������ ����������
�������� ����, � ��������� �� ��� ��, ��������� ���
���������� ����� �������������� ��������� �
������������� �����. ������ ������������� �� ������
����� � �������� Ttl-inc.txt.


6.5.15. �������� ULOG

�������� ULOG ������������� �����������
�������������� ������� � ���������������� ������������. ���
�������� ������������ �������� LOG, ������������ �� ���������
�������. ��� ������������� ����� ��������, �����, �����
������ netlink, ���������� ������������ ������ �������
����� ��������� ����� ��������� �������������� � ���������
�������� (������� ��������� ����, ���� ������ MySQL � ��.)
� � ���� �� ������������ ����������� ���������� ���������
(��������) ��� ������������ ��������� �������� �������� �
��������� ������� ����������. ���������������� ����� ULOGD
�� ������ �������� �� �������� �������� ULOGD project page.

������� 6-25. �������� ULOG

���� —ulog-nlgroup
������ iptables -A INPUT -p TCP —dport
22 -j ULOG —ulog-nlgroup 2
�������� ���� —ulog-nlgroup ��������
ULOG � ����� ������
netlink ������ ���� ������� �����. ����� ����������
32 ������ (�� 1 �� 32). ���� �� ������� ��������
����� � 5-� ������, �� ����� ������ ������� —ulog-nlgroup 5.
��-��������� ������������ 1-� ������.
���� —ulog-prefix
������ iptables -A INPUT -p TCP —dport
22 -j ULOG —ulog-prefix «SSH connection
attempt: «
�������� ���� —ulog-prefix ����� ���
�� �����, ��� � ����������� ����� � ��������
LOG. ����� ������
�������� �� ������ ��������� 32 �������.
���� —ulog-cprange
������ iptables -A INPUT -p TCP —dport
22 -j ULOG —ulog-cprange 100
�������� ���� —ulog-cprange
����������, ����� ���� ������, � ������, ����
���������� ������ ULOG. ���� ������� �����
100, ��� �������� � �������, �� ������ �����
�������� ������ 100 ���� �� ������, ��� ��������,
��� ������ ����� ������� ��������� ������ �
��������� ����� ������� ������ ������. ���� �������
0, �� ����� ������� ���� �����, ���������� �� ���
�������. �������� ��-��������� ����� 0.
���� —ulog-qthreshold
������ iptables -A INPUT -p TCP —dport
22 -j ULOG —ulog-qthreshold 10
�������� ���� —ulog-qthreshold
������������� �������� ������ � ������� ����.
��������, ���� ������ �������� ������ ������ 10,
��� � �������, �� ���� ����� �����������
������������� ������ �� ���������� ������ �
���������� � ���������������� ������������ ��������
�� 10 �������. ��-��������� ������ ������ ����� 1
��-�� ���������� �������� ������������� � �������
�������� ulogd, ������� �� ����� ��������� ������
�������.


����� 7. ���� rc.firewall

� ���� ����� �� ���������� ��������� ����������� �� �������
�������� rc.firewall.txt. �� ����� ����� ������ �������
��������� � ������������� ��� ��� �������� � ��� ������. ���
����� ���������� ��� �� ������� ����� ����������� �����. ���
������� ����� �������� ��� ����������� ������ � ���� ���������
����� �������, ����� �� ��� �������� � ����� �������������
����, � ����������� ������� ���������� �������� ������
����������.

Note

�������������, ��� ���� ����� ����������� �������
������� ������� ������, ������ � ������� �� ����� �
������� ��������������� ��������, ���, ����� ������
���� ������ ��� ��� �������� �������� ��������
BASH.


7.1. ������ rc.firewall

����, ��� ������ ��� ������� ����� ������� rc.firewall.txt (��������
������� � ������ ������� ��������� � ���������� ������� ���������). ��
���������� �����, �� ������ ��-�� �������� ����������
������������. ������ � ��������� ��� ����������� ���� ����,
����� �������� ������������� � ��� ���������� � �����
��������� ���� �� ����� ���������� �����������.


7.2. �������� ��������
rc.firewall

7.2.1. ������������

������ ����� ����� rc.firewall.txt
�������� ���������������� ��������. ����� �������� ��������
��������� �����������, ������� ������� �� �����
������������ ����. �������� IP ������ — ��������� ������
���� �������� �� ���� �����������. ���������� $INET_IP ������ ���������
�������� IP �����, ���� �� ������������� � �������� �����
DHCP, �� ��� ������� �������� �������� �� ������ rc.DHCP.firewall.txt,
���������� $INET_IFACE ������ ��������� ����
����������, ����� ������� �������������� ����������� �
��������. ��� ����� ����, � �������, eth0, eth1, ppp0, tr0
� ��.

���� �������� �� �������� ����� ���� ��������,
����������� ��� DHCP, PPPoE, ������� ��� ������� ��
���������. �� �� ����� �������� � ������ «������»
��������. ��� ������� �������������, ����� �� ����� �����
�������� ������ ������� ����� ����������. ���� ���
����������� ��������� ��� �������, �� �� ������ ����� �� ��
������ ��������, ��� �������� ���� �����������.

������ Local Area Network ������ ���������
���������, ��������������� ������������ ����� ���������
����. �� ������ ������� ��������� IP ����� �����������,
���������, ������������ � ��������� ����, ����� ������� �
����������������� �����.

����� ������� ������ Localhost Configuration, �������
�������� ��� ���� �� ��������. � ���� ������ �����������
��������� ��������� lo � ��������� IP ����� 127.0.0.1. ��
�������� Localhost Configuration, ������� ������ Iptables
Configuration. ����� ��������� ���������� $IPTABLES, ���������� ���� �
����� iptables (������ /usr/local/sbin/iptables). ���� ��
������������� iptables �� �������� �������, �� � ��� ���� �
iptables ����� ��������� ���������� �� ������������ �
�������� (�������� /usr/sbin/iptables), ������ �
����������� ������������� iptables ����������� ������
�����.


7.2.2. �������� ��������������
�������

� ������ �������, �������� /sbin/depmod -a, �����������
�������� ������������ ������� ����� ���� ������������
��������� �������, ����������� ��� ������ ��������.
���������� � ����� ��������� ��������� ������ �����������
������. ��������, �� ����� �� �������� �� ������� ���������
�������� LOG, REJECTMASQUERADE � ���� ������������
������� � ������ ���������� ������� �������, ������������
��� ��������, ����� ��������������� ������ ����������
��������� ���������:

/sbin/insmod ipt_LOG
/sbin/insmod ipt_REJECT
/sbin/insmod ipt_MASQUERADE
   
Caution

� ����� ��������� � ������������� �������� ���
����������� ������, �� ��������� �������. ����
���������� ������ �� ����� �������� ������, ��
������ ����� ���� ���������, �� �������� ��������
�������� ��, ��� ������������ ������ ��������������
� ����� ����������. �� �������������� �����������
����������� � ������� �������� ��������
�������
.

� ��������� ������ ���������� ��� �������, ������� ��
������������ � ������ ��������, �� ����������� ��� �������.
��� �������� ������ ipt_owner, ������� �����
�������������� ��� �������������� ������� � ���� � �����
������ ������ ������������� ����� �������������, �������,
��� ����� ������� ������������. ���������� �� ��������� ipt_owner, �������� � �������
�������� Owner ����� ��� �������
�������
.

�� ����� ��������� �������������� ������ ��� ��������
«���������» ������� (state matching). ��� ������,
����������� ����������� �������� ��������� �������,
��������� ��� ip_conntrack_*ip_nat_*. � ������� ���� �������
�������������� ����������� ���������� �� �����������
����������. ��������: �������� FTP �������� �����������
���������� �� �����������, �� �������� ���������� �
���������� � ������� ������ ������. ���, ���� ��� ���������
���� �������� ����� ����������, ������������ ����������
�������, ������ �� ���������� � FTP �������� � ��������, ��
������ ������ ���������� ��������� IP ����� �����. �
���������, IP ������, ����������������� ��� ���������
�����, ��������� ���������� � ��������, �� ������ �� �����
����� ��� ������ � ���� ��������, � ���������� ����������
�� ����� �����������. ��������������� ������ FTP NAT
��������� ��� ����������� �������� �� ��������������
�������, ������� FTP ������ ���������� ������� ������ ��
���������� �� ����� ������ �������� IP ������ � ������
���������� ����������. �� �� ����� ���������� ���
������������� DCC ��� �������� ������ � �����. ���������
���������� ����� ���� ������� �������� IP ������ � ����� ��
��������� IRC, ������� ��� �� �������� ����� ����������
������� ������� �� �����������. ��� ������������ ������
���������� ����������������� ���������� FTP � IRC
���������� ������ ������������. ��������, �� ������
��������� ����� ����� DCC, �� �� ������ ����������. ���
��������������� ���, ��� DCC «���������»
����������. �� ��������� ������������ ���� � ����� �������
�������� ���� � ���� �� ������ ������������. ���
���������������� ������ DCC ���������� �������� ���, ���
���� �� �� ����������� ������������ ���������� ��������
��������� � ����� � ����� ��������� ����, ����� ������
����� ���������� ����� «��������». ���
������������� �� ���������������� ������ ��� ��������
���������. ��������� ��������� ���������� ���������� IP
����� ��� ������������ ����������.

Note

���� � ��� ����������� �������� � ������������
mIRC DCC ����� ����������, �� ��� ���� ������
IRC-������� �������� ������ ��������� — ����������
������ �������� mIRC DCC
���������� ����� �������� �
�������
.

�������������� ���������� �� ������� conntrack � nat
������� � ���������� ����� �������� �
�������
. ��� �� �� ��������� � ������������,
���������� � ����� iptables. ����� ����� ��� ��������������
�����������, ��� ����������� ���������� patch-o-matic �
����������� ����. ��� ��� ������� — ����������� ���� �
����� ����������.

Note

��������, ��� ��������� ������ ip_nat_irc �
ip_nat_ftp ��� ����������� ������ � ��� ������,
���� �� ������, ����� �������������� �������
������� (Network Adress Translation) �������������
��������� � ����������� FTP � IRC. ��� �� ���
����������� ���������� ������ ip_conntrack_irc �
ip_conntrack_ftp �� �������� ������� NAT.


7.2.3. ��������� /proc

����� �� ��������� ��������� ������� (IP forwarding),
������� ������� � ���� /proc/sys/net/ipv4/ip_forward �����
��������:

echo «1» >
/proc/sys/net/ipv4/ip_forward

Warning

�������� ����� ���������� ��� ��� ��� � �����
�������� ��������� (IP forwarding). � ���� � �
������ ��������� � ������ �����������, �� ��������
��������� �� ���� ��� �������� ����� ���� �������
iptables. �� ������ ������ ��������� (IP
forwarding) �� �������, ����� ����� �������
����������� �������, ��� ����� ��������, �����
������ �� ���������� ����������� �� �����, ���
������� �� ������ ������, ����������� ��������� �
�������������� ����������� ����������. �������, ���
��� ���� ��������� ���������� �������, �����
������������� ����� ���������� ����� ����������.
�������, � �������� �������� ��������� ���������
(IP forwarding) ������� ����� �������� ����� ������
������. ����� �� � �������� ��������� ��������� �
������ ������������� � ����� ���������������.

���� ��� ���������� ��������� ������������� IP, (���
������������� SLIP, PPP ��� DHCP) �� ������ ���������������
������:

echo «1» >
/proc/sys/net/ipv4/ip_dynaddr

���� ��� ��������� �������� ����� ������ �����, ��
������ ���������� � ��������������� ������������ �� ����
������. ������� � ���������� �������� �� �������� �������
/proc ������������ ������ � �����. ������ �� �� ������
��������� �� ������� � ���������� ������ �� ������
�������
.

Note

�������� rc.firewall.txt � ���
��������� �������� � ������ �����������, ��������
��������� �� �������� ������ �� ���������
(non-required) �������� /proc. ��� ��
�������������� �� ��������� ��� ����� — ��
��������� ��, ���� �� ���������, ��� ����������
����� ������������� ���� �������, ������� ���
���������.


7.2.4. ���������� ������ �� ������
��������

����� �� ��������� � ���������������� ��������, �
��������� — � ���������������� ��������, ������������ �
�������� rc.firewall.txt. ��� �������
���������� ������ �� �������������� �������� �����
��������� ������������ � ��� ��� ���� ���������� ������. �
�������, ��� ����� �������� ��� ��������� «���������
�����». ������ ������ ����� ������������� � ������ ������� ����������� ������
� �������
� ���������� �������� ����� ��� ���,
���� �� �����, ����������� ��.

����������� ����� ������ �� ���������������� ��������, �
������� �������� ������������� �������, ��� ������ ������
������������ ������� � ������������� ���������. ������
����, ����� ���������� TCP ������ ����� ���� ����� ������
(� ��� ICMP, � ��� UDP), � ������ ������� TCP ������ � ��������� �� �����
���������������� �������, ��������������� ������ ��� TCP �������, ��� �������� �
���������� �������� �� �������. �� ��������� ��������
���������� ���������� ������� ����������� ������� �����
netfilter. � ����������������, ��� �������� ��������
��������� ����������� �� ��������� �� ������, ����������� �
����� ������� ����������� ������
� �������
.

�������� ���������� ������� — �������� ���� ������. �
�����, ������ ������ �������� ������� �� �������������, ���
�� ����� ���� ��������� ����, ���� ���������� (firewall) �
������������ ����������� � ��������, � ���������� IP
������� (� ����������������� PPP, SLIP, DHCP � ������). ��� ��
��������������, ��� ������ � �������� �������� ���� �����
����������, ��� �� ��������� �������� ����� ��������� ����
� ������� �� ���������� ����������� �������, ��������� ��
��������� ����, ������ �������� �� ����� ���������
������������� ����� � ������� ���������� ����������
����������� ������� � ���� ��������� ���� �����. ��
���������� �������� �� �������� «��� ��� �� ���������
— �� ���������». ��� ���������� ����������
�����������, �� ������������� �������� ��-��������� —
DROP. ��� ����� �� ��������
����������, ������� ���� �� ���������.

� ������ ������� ���������� ��� ��� ����� ������� �
���.

��� ������ — �������� ���������� �� ��������� ���� �
��������. ��� ����� ��� ����������� ���������
�������������� ������� ������� (NAT). �������� ��� � ������� PREROUTING (� �������, ��� ����� ����� ������
�������� ��������, ��������� � ������ �������� �����������
������� POSTROUTING, �� � �� ��� �����, ��� SNAT
������������ � ������� POSTROUTING ������� nat ����. �����.)
, �������
����������� ��������� � ����� ��������. ���������������,
�����, ���������� ��������� ���������� � ������� FORWARD. ���� �� ��������� ��������
����� ��������� ����, ��������� ���� ������� � ��������, ��
��� ��� �� �������� ������� � �������� �, �������������
���������� ������� ����������� �� ������ � �����
����������� �����. � ����� ������ �� ��������� �����������
������� � ���� ���� ������ � ������ ��� ��������������
����������, ���� � ������ �������� ������ ����������, �� �
������ ��� ������������� (ESTABLISHED � RELATED).

��� �������� ������-����������� — ���������� ��
�������� ������ �������, ���������� � ��������.
������������� �� ��������� ������ HTTP, FTP, SSHIDENTD ������ � �����������. ��� ���
��������� �� ����� ������� ����������� � ������� INPUT, �������������� ��� ����������
��������� «��������» ������� � ������� OUTPUT. ��������� �� ������������
������������� ��������������� � ��������� �����, �� ��
��������� ������� ��� ��������� ������� ��������� ����, �
������ � ��� ���������� �������� ���������� � ���������� IP
������ (127.0.0.1). ��� ��� ����������� ����, ����������
��� ���������� �������, ���������� ���������� ��� ���������
�����, ��� ������ ��������� � �������� ���������� � ���
������� �� �������������. ������� � �� �������� �����
������� �� �������� � ��������� �������, �������������
���������� ��������� �����. � � ���������� ���������� �����
����� �������� �
�������
.

��� ��� � ��� �������� FTP ������, �� �������,
������������� ���������� � ���� ��������, ���������� ����
�� ��������� � ������ ������� INPUT, ��������� ��� �����
���������� �������� �� �������. � ����� ��, ���� ��������,
��� ��� ������ ������ �������� �����, ��� ������ ��������
������������� �������, ��� ���� �������� �� �������. � ����
����� � ������ ����� ������ �� �������������� �������.

� ����� ������� � ������ ������ �� ������ �� ��
�������������� � ���� ��� ����� ���������. ��� ������� ����
��������� ������� ���� ������� ������, ��������, tcp_packets, ������� ��������
������� ��� �������� ���� ���������� TCP ������ � ����������. ���
���������� �������������� �������� �������, ��������� �����
���� �������, ����� ���� ������� ������. � ����� ������
������� �������� ������� allowed. � ���� ������� ������������
�������������� �������� ��������� ������������� TCP ������� ����� ��� ��� �������
������������� ������� � ��������. ICMP ������ ������� ����� �������
icmp_packets. ����� �� ������
���������� ��� ICMP ������ � ��������� �����
���������. � ������� UDP ������. ��� �������� �����
������� udp_packets, ������� ������������
�������� UDP ������. ���� ��� �����������
���������� ��������, �� ��� ������������ ��� ����������
�������������� ��������.

��������� �� ������������� ������������ ��������� ����,
�� ��� ���������� ������������ ��� � � �������� �������
�������, ������� �� ������ ��������� ���������� � ��������
� � ������ �����������.

� � ���������� � ������� OUTPUT. �� �� ��������� ����� ����
����������� ���������� ��� �������������, ������ �� ��
�����, ����� ��� ����, ��������� ��� ���������� ������� �
���� «����������» ������, ������� ��
������������� �������, ����������� ����������� �������
������ � ����� ������� � ��������� ����, � ����� ���������
������� (127.0.0.1) � � ����� ������� � ��������. � ����
������� ������ ������������ �������� OUTPUT, ��� ��������� (������ �����
�������������������) ���������� ��������� ��-��������� DROP.


7.2.5. ��������� �������
��-���������

������, ��� ���������� � �������� ������ ������,
���������� ������������ � ���������� ������� ��-���������.
�������� ��-��������� ��������������� ��������, ��������
���������� ����

iptables [-P {chain}
{policy}]

�������� ��-��������� ������������ ����� ��������,
������� ����������� � ������, �� ��������� ��� �������� ��
������ �� ������ � �������. (��������� ���������, ������� iptables -P ��������� ������ �
���������� ��������, �.�. INPUT, FORWARD, OUTPUT � �.�., �
�� ��������� � ���������������� ��������. ����. �����.).

Caution

������ ��������� ��������� � ���������� �������
��-��������� ��� ������� �� ������, ��
��������������� ��� ����������, ��� ��� ��� �����
��������� � �������� �������� �����������.


7.2.6. �������� ����������������
������� � ������� filter

����, � ��� ����� ������� ��������� ��� ����� ��������
�������� ������� ����� ��������� �������, � ��� ��� �������
��������������� ����� �����! �� ��� ������ ����
������������ ���� ���� � ���������� ������� ��������.
������� ������ ��������� ������� � ������ ������ ���
���.

������ ����� ���������� ������� �������������� ������� �
������� ������� -N. ����� ����� �������� �������
��� �� ����� �� ������ �������. � ����� ������� ���������
������� icmp_packets, tcp_packets, udp_packets � ������� allowed, ������� ���������� ��
������� tcp_packets. �������� ������ �
���������� $INET_IFACE (�.�. �� ��������),
�� ��������� ICMP ���������������� � ������� icmp_packets, ������ ��������� TCP
���������������� � ������� tcp_packets � �������� ������ UDP � ���������� eth0 ���� � �������
udp_packets. ����� ���������
�������� �� ������� � ������� ������� INPUT. ���������
������� ��� �������� ����� ������� ����� �����:

iptables [-N chain]


7.2.6.1. �������
bad_tcp_packets

��� ������� ������������� ��� ���������������� �������
� «�������������» ����������� � ������� ����
������ �������. ����� ����������������� ��� ������,
������� ������������ ��� NEW, �� �� �������� SYN ��������, � ��� ��
�������������� SYN/ACK-������, ������� ������
NEW. ��� ������� ����� ����
������������ ��� ������ �� ��������� � ������������
������. ����, ��� ��, ��������� ������� ��� ����������
������� �� �������� INVALID.

���� �� ��������� �������� ����� �������� �� ����
��������, �� �������� ������ ������ �� �������� NEW � ��
���������� ����� SYN
� ���������� ����� �������� �
�������
. ����������, �� ������ ����������� �����
������ ���������� ������ � ��������� NEW � ���������� ����� SYN, �� � 99% ������� ���
����������� ���. ������� ��� �������� ������� ����������
� ����� ������� � ��������� ������, � �����
«����������» ��.

�������, �� ������� ��� SYN/ACK-������� �� ��������
NEW ����������� �������� REJECT, ���������� ������. ���
����������� � ������� SYN/ACK — ������ � ������ ��
�������� NEW
���������� ����� �������� �
�������
. ������������ ��������� �������������
����������� ������ RST � �������� ������� (RST � ����� ��
������������� SYN/ACK). ��� ����� �� �������������
����������� ����� «������������ ������
TCP-������������������» (Sequence Number Prediction)
�� ������ ���� ����.


7.2.6.2. ������� allowed

TCP �����, ������ � ���������� $INET_IFACE, �������� � �������
tcp_packets, ���� ����� ������� ��
����������� ����, �� ����� ����� ����������
�������������� �������� � ������� allowed.

������ ������� ���������, �������� �� ����� SYN �������, �.�. �������� ��
����������. ����� ����� �� ������� ���������� �
����������. ��������� ������� ���������� ��� ������ �
��������� ESTABLISHED ��� RELATED. ����� ����������
��������������� SYN �������, � �� ���� ������ ���
��������� ������������� �����, �� ��� �������� ������ ESTABLISHED. ��������� �������� �
���� ������� ������������ ��� ��������� TCP ������. ���
��� ������� �������� ������ �� ���������������
����������, ������ �� ���������� ����� SYN, ������� �������� ���������
����������. �� SYN ������ ����������� ��
������������ ��� ������� ����������, �� �����������
������� ������������ ������. ��������� � ����, ��
����������� ���� ��� ���������� TCP/IP, �������
������������ �� �������� ���������� �����, ��� ��������
SYN ������, ������� �� 99% �����
���� ���������, ��� �������� ������, ��������� ��������
������.


7.2.6.3. ������� ��� TCP

����, �� ������� � TCP �����������. ����� ��
���������, ����� ����� ����� ���� �������� �� Internet.
�������� �� ��, ��� ���� ���� ����� ������ ��������
�����, �� ��� ����� ��� ������ �������� � ������� allowed ��� ��������������
��������.

� ������ TCP ���� � ������� 21, ������� ��������
������ ���������� FTP ������������. � �����, � ��������
��� RELATED ����������, ��������,
��� �����, PASSIVE FTP, ��� �������, ��� ��� ��������
������ ip_conntrack_ftp. ���� ���
����������� ��������� FTP ����������, �� ��� �����������
��������� ������ ip_conntrack_ftp � �������
������ $IPTABLES -A tcp_packets -p TCP -s 0/0
—dport 21 -j allowed
�� �������� rc.firewall.txt.

���� 22 — ��� SSH, ������� ������� ����� ��������� ���
telnet �� 23 �����. ���� ��� ���������� ������������
������ � ��������� �������� (shell) ���� �� �� �� ���� ��
��������, �� ����� ������� ������������ SSH. ������ ,
���� ��������, ��� ������-�� ��������� ������ �����
������������� ������ � ����������� ������ ����� ���
�����. ��� ������� ����� ������ ����� ������ �� �������,
������� ������������� ���������� � �� ����� ����.

���� 80 — ��� ���� HTTP, ������ ������� — web ������,
������� ��� �������, ���� � ��� ��� web �������.

� ������� ���� 113, ������������� �� ������ IDENTD �
�������������� ���������� ����������� ���� IRC, � ��.
������, ��� ��� ������� ������������ ����� oidentd ���� �� �������
���������� ������� ������� ��� ��������� ����� (������) �
��������� ����. oidentd ������������ ��������
IDENTD �������� � ���������
����.

���� � ��� ������� ������������� �������
�������������� �����, �� ������ ���������� ���� �� ������
� ������� tcp_packets � ���������� ������
������ � ������������ � ������ ������������.


7.2.6.4. ������� ��� UDP

������ UDP �� ������� INPUT ������� � ������� udp_packets ��� � � ������ � TCP ��������, ����� ���
����������� �� ������������ �� ������ ����� ����������.
�������� �������� — �� �� ��������� ��������� ����
������, ��������� �� ���� ��������� �������� �����������
���������. ����������� ������ �� �����, �������
������������� ��������� ��� �������� �� �����
�����������. ������, ������� ��������� �� ���������� ��
��� ������������� ����������� (������������� �� ���������
����) ������������ ������������ �������������, ���������
����� ��������� ESTABLISHED ��� RELATED.

��� ����� �� ������ ��������, ���� 53, �� �������
«�����» DNS, ��� UDP ������� ������, �� ����
�������, ����������� 53-� ���� � �������� ������������,
�� ����������������. ���� �� ��������� ��������� DNS ��
�����������, �� ��� ������� �������
�����������������.

� ����� �������� ���� 123, �� ������� �������� NTP
(network time protocol). ���� ������� ������ ����������
��� ������ ������� ������� � �������� ������� � ��������.
������, ��������� �����, ��� �� �� ����������� ����
��������, ������� ��������������� ������� � �������� ���
�� ����������������.

���� 2074 ������������ ���������� ���������������
������������, ������� speak freely, ������� ������������
��� �������� ������ � ������ ��������� �������.

� ������� — ICQ, �� ����� 4000. ��� ������ ���������
��������, ������������ ICQ-������������ � ������� ��
������� ��������� ��� ��� ��� �����.

����� ���� � �������� ��������� ��� ��� �������,
������� ��-��������� ����������������. ��� �����
���������������, ���� ���������� ��������� ��������.
������ — ��������� ����������������� ������, �����������
�� ����� �� 135 �� 139. ��� ����� ������������
����������� SMBNetBIOS �� Microsoft. �����
������� ������ ������� ������������� ������������ �������
������������� � ����� Microsoft Network. ������ �������
��������� DHCP ������� �����. ��� �������
����������� ����� ����� ���� ������� ���� ��������
��������������� ��������, ��� IP ������ ����������
�������� �����������.

Note

��������� ��� ������� �� ��������
������������� (� ������ �������� ���
����������������). ��� ������, ������� �� ����
���������� ��� ������� ����, ���������� � ������
��������� �������� � ������� INPUT, �������, ���� ���
��������� �������� «����������»
���������� ������� — ������ �����������������
��� �������.


7.2.6.5. ������� ��� ICMP

����� ����������� ������� � �������� ICMP �������. ���� ����� ��������
� eth0 � ������� INPUT, �� ����� ��
���������������� � ������� icmp_packets. � ���� �������
����������� ��� ICMP ���������. ������������
������ ICMP Echo Request, TTL equals 0 during transitTTL equals 0 during reassembly.
��� ��������� ���� ICMP ��������� ������ ���������
���������� ����������������, ��������� ����� �����
��������� RELATED.

Note

���� ICMP ����� �������� �
����� �� ��� ������, �� �� ����������� ������ RELATED (��������� �
��������� �����������). ����� �������� ���������
������� ��������������� � ����� �������� �����������
���������

��� �������� ������� � ������ �� ���������
�����������: ICMP Echo Request ������
����������, ������� �������, ��� �������� �����������
�����. ���� ������� ��� �������, �� ��� ���������� ��
����� «�����������» � ����� �� ICMP Echo Request, ��� �������
������������� ������� ping � �������� ��, �� ��������� �
�����������, ������������.

Time Exceeded (�.�., TTL equals 0 during transitTTL equals 0 during reassembly).
�� ����� �������� ������ �� ����, �� ������
�������������� ���� TTL, � ��������� ������,
����������� �� 1. ��� ������ ���� TTL ������ ������ ����, ��
��������������� ����� ������� ��������� Time Exceeded. ��������, ����� ��
���������� ����������� (traceroute) ������ ���� ����, ��
���� TTL ��������������� ������ 1, ��
������ �� �������������� ��� ���������� ������ ���� � �
��� �������� ��������� Time Exceeded, �����,
������������� TTL = 2 � ������ ������������� �������� ���
Time Exceeded, � ��� �����, ����
�� ������� ����� � ������ ����.

������ ����� ICMP ��������� �������� �
���������� ���� ICMP ��������������
���������� �� ICMP �� ������ �������� �
��������� ����������:

  • The Internet Control Message
    Protocol

  • RFC 792 — Internet Control
    Message Protocol
    — �� J. Postel.

Note

������ ����������� ��� ������������ ICMP �������, �������� �
�� ����, �������� �����-�� �� ���, �����
��������� ���, ��� ��� ��� ��� �����������.


7.2.7. ������� INPUT

������� INPUT, ��� � ��� �����, ���
���������� �������� ������ ���������� ������ �������, ��
���� ���� ������ �������� �� ������� ������. ������
���������� ������ �������� ����������� ������ ����� �������
�� ��������� �������, ������� � ������ ������ ��������
«������» ������ ��� ������� ��������. �����������
��� ���������� ������ ������ �� ���������� �������� �
��������� �� � ��������� �������. ��� ����� �����������
���������� ������, ������� �������� ������ �����.

������ �� �������� �� �������� ���������
«������» ������. �� �������������� �����������
����������� � ���������� �������
bad_tcp_packets
. � ��������� ��������� ���������
����� ������ ����� ��������� �����������, �� � 99% �������
����� �� «����������». ������� ����� ������
��������� � ��������� ������ (����������) �
«������������».

����� ������� ����� ������ ������, ������� ����������
���� ������, ������ �� ������������� ����, ������� ��������
� ���� ������� �������, ��������� � ��������� ����� �
��������� ������� ��������� (lo) � ������� �������� ������
����� ��������� ���� (������� �������� IP �����). ���
������ ������ ����� ������ �� ��� ������� �������, ���
��������� ���� ���������� ����������� ������� ������ ���
������ �� Internet. �������, ��� ���������� ����� �������
������, ������ ���������� ��������� ����� �������, ��������
������� �� �������, ������� ����� ����������� �������
������.

������ � ������, ������������� ������ ������ �
$INET_IFACE, ����� �������, ������������ ��� ������ ��
�������� ESTABLISHED ��� RELATED (��� ������ ��������
������ ��� �������������� ��� ���������� ����������). ���
������� ������������ �������, �������� � ������� allowed. �
� ��������� ������� �������� ����������, ��������� �����
������� allowed ���������� ������������� ����� �������
tcp_packets, ������ ��� ��������� ���������� �������
������, ��������� ������������ ���� ������� ������������
���� ������� � �� �������� ��� ������������������ ��
������� allowed.

����� ����� ������������ ������ �������, ������� ��
Internet. ��� ������, ���������� � ������� INPUT � ���������� $INET_IFACE �������������� ��
��������� ��������, � ����������� �� ���� ���������. TCP
������ ���������� � ������� tcp_packets, UDP ������ ������������
� ������� udp_packets � ICMP ����������������
� ������� icmp_packets. ��� �������, �������
����� ������� «�������» TCP ������, ����� UDP �
������� ����� ���������� �� ���� ICMP, ������ � �����
���������� ������ ��� ������������� ����� ���������
��������. ����� ����� ��������� ����� �������, �����������
����� ����� ������. ���� ������ ������� — ����������
�������������. � ������ �������������� ������������� ������
���� ������ ������ Pentium III � ����, � ������� ������ 100
���� � ������� ������� ������������ ������ �� ����,
�������� ����� ����� «��������� �� ������»
������������ ��������� ������� ������.

����� ������� ������ ������������� ������� (��-���������
����������������). ���� � ���, ��� ������� Microsoft
Network ����� «������ ��������» �������� ��������
���������� Multicast (���������) ������� � ���������
������� 224.0.0.0/8. ������� ����� ������������ ������
������� ��� �������������� «���������» ����� �
������, ���� � ������� ������� ������� ����� ���� ����
Microsoft Network. �������� �� �������� ������ ���
��������� ������� (��-��������� ����������������) � �������
udp_packets, ��������� � ������� ��� UDP.

��������� ��������, ����� ��� ��� �� ���� �� ��������
���� ������� � ������� INPUT ����� ��������� ��������
��-���������, ������� �������������, �� ������
������������� ������ ������ ����������� �������. ��� ����
�� ������������� �������, ����������� �� ����������
���������� ������� — �� ����� 3-� � ������, �����
������������� ���������� ���������� ������� � ����� ����
�������� ������ � ������ �������������� �����������
������������ (���������), ����� ����� ������ ��������� ���
������.

��� ��� �� ���� ���� ��������� � ������� INPUT �����
����������� �������� DROP, ��������� ������ ���
�������� ��������� � �������� �������� ��-���������.
�������� ��-��������� ���� ������� ���� ���� � ������� ��������� �������
��-���������
.


7.2.8. ������� FORWARD

������� FORWARD �������� ����� ���������
���������� ������. ������ ������� ��������� ��� TCP ������
�� �������� � ������� bad_tcp_packets, �������
������������ ��� �� � � ������� INPUT. ������� bad_tcp_packets ���������������
����� �������, ��� ����� ���������� �� ������ �������,
�������� �� ��, ���� ������������ �����. ����� �������� TCP
�������, ��� ������, �� �������� �������� ������� ��
��������� ���� ��� �����������.

�����, ������������ ���� ������ �� ��������� ���� ���
�����������. �����������, ����� ���������� �������� ������
� ��������� ����, ������� ��������� �������� �� ����������
���, ��� ����� ������� ESTABLISHED ��� RELATED, �.�. ��
���������� ������ �� ���������� �������������� �� ���������
����.

� � ���������� ������� � ��������� ������ ���������� �
���������� �������, ��������� �� ��������� «IPT FORWARD packet died:
«
, ����� �����, � ������ ������ ������, ��
���������� �� � ��������, ����������� � ������� INPUT.


7.2.9. ������� OUTPUT

��� � ��� �������� �����, � ���� ������ ���������
������������ ��� ���������� � ������������ ��� �������
�������. ������� � �������� �������� ��� ���� �����, ���
����� �������� ����� $LOCALHOST_IP, $LAN_IP ��� $STATIC_IP. ������� ��� ���
������ �� �������, ������� ����� �������������� �����
����������, �������� �� ��, ��� � ���������� ������ ��
����, ��� ����� � ���� ������. � � ���������� �� �����, �
���������� «����������» ������, �� ������ ������
������ ��� � ����� ��������� ������������������� �������.
�� ���� �������, �� ��������� �� ���� �� ������,
����������� �������� ��-��������� — DROP.


7.2.10. ������� PREROUTING �������
nat

� ������ �������� ��� ������� �� ����� �� ������ �������
� �����������, ������ � ������� �� �������� �����, ��� ���
��� ���������, ��� � ������ ������� �����������
�������������� ������� ������� (DNAT) ����� ��� ��� ������
������� � ������� INPUT ��� FORWARD.

Caution

��� ��� ���� ���������, ��� ��� ������� ��
������������� �� ��� ������ ���� ����������, �
������ ��� �������������� �������, ��������� � ���
������� �������� ������ ������ ����� �� ������.


7.2.11. ������ SNAT � �������
POSTROUTING

� �������������� ������ — ��������� SNAT. �� ������� ���� ��� ����.
������ ����� �� ��������� ������� � ������� nat, � �������
POSTROUTING, ������� ����������
�������������� �������� ������� ���� �������, ��������� �
����������, ������������� � Internet. � �������� ���������
��� ����������, � ������� ������� ����� ������������ ���
�������������� ��������� ��������. ����� ����,
������������� ���������� �������� ��������������� ��������.
������ -t �������� ��� �������, � ������
������ nat. ������� -A ��������� (Add) ����� �������
� ������� POSTROUTING, �������� -o $INET_IFACE ������ ���������
���������, � � ����� ������� ������ �������� ��� ������� —
SNAT. ����� �������, ��� ������,
���������� ��� �������� �������� �����
«�������������», �.�. ����� ��������� ���, ���
����� ��� ���������� � ������ ����. �� �������� �������
���� —to-source � ��������������� IP
������� ��� ��������� �������

� ���� �������� � ��������� SNAT ������ MASQUERADE �� ���� ������. ������
— ��������������, ��� ���� �������� ������ �������� ��
������� ����, ������� ����� ���������� IP �����. ���������
������� � ���, ��� SNAT �������� ������� � �����
����������. �������, ���� �� �� ������ ����������� IP
������, �� �� ������ ������������ �������� MASQUERADE, ������� �������������
����� ������� ������ ���������� �������, ��������� ���
������������� ���������� IP �����, ����������� ���������
����������. ������, �� ��������� � SNAT ��� �������� �������
��������� ������� �������������� ��������, ���� � ��
�����������. ������ ������ � MASQUERADE, �� ������� � ��������
rc.DHCP.firewall.txt.


����� 8. ������� ���������

���� ���� ����� ������� � ���, ����� ���� ������� ��������
������� ��������, � ���� �����������. ��� �������� ��
����������, � ��� �� ����� ��������� ��������������� �����
������. ��� ��������, ��� �� ������ ���� «���������»
��� �������� ��� ����. ����������� ����� ����������� ��������
��������� ��� ��� ��������.


8.1. ��������� �����
rc.firewall.txt

��� ��������, ��������� � ���� �����������, �����
������������ ���������. ������� ��� ��� ����, ����� ��������
���� ����������� ������ ���� �� �����, �������� ��� �����
����� �������� ����� ����. ��� ��������� �������� ������
����������� � ���� �����. ����� � ������� ���� ��� ���������,
������ ��� �������� ���� �������� ������ ��� � ������ �
������ ������ ��� ���������.

Note

�������� �������� �� ��, ��� ��� ��������� �����
��������� ������ ������������� ��� ����� ���������.
��� ��������� ������� ���� ��� ������� ����������
���� ���� ������.


8.1.1. ���������

��� — ���������, ������� ������� ��� �������� � ����
�����������. ���� �� ����������, ��� ��� �� ���, �� ������
����� ��� ��� ������, ���� ������� � �� ��������, ������ �
������� ��� ���������.

  1. Configuration — ������ ����� ��
    ������ ������ ��������� ������������, ��� ��������.
    ��������� ������������, � ����������� �������, ������
    ���� ������� ������� � ����� ��������.

    1. Internet — ��� ������
      ������������, ����������� ����������� � Internet.
      ���� ������ ����� ���� ������, ���� �� ��
      ���������� � ��������. �������� ��������, ��� �����
      ������� ������� ���������� ����������� ���, �����
      �����������, �� ������ ��, ������� ��������� ����
      ����������� � Internet.

      1. DHCP — ���� �������
        ����������� ��� DHCP ���������, �� ���
        ����������� �����.

      2. PPPoE — �����������
        ��������� ��������� PPPoE �����������.

    2. LAN — ���� ������� �����
      ��������� ���� �� ������������, �� �����
      ����������� ���������, ������� ��������� � ���.
      �������� ��������, ��� ���� ������ �����
      �������������� ����� ������.

    3. DMZ — ����� �����������
      ������������ ���� DMZ. � ����������� ���������
      ����� ������� �� �����, �.�. ����� ����������
      �������� ����, ��� ��������� ��������� ����, ��
      ����� ����� ��. (DMZ — de-militarized zone.
      ������ ����� ��� ��� ������� ����� ������ ���������
      �������, � ������� ����������� �������, ��������:
      DNS, MAIL, WEB � �.�, � ��� �� �����
      ���������������� ������. ����. �����.)

    4. Localhost — ��� ���������
      ����������� ������ ����������� (localhost). � �����
      ������ ��� ���������� ���� �� ���������, ��, ��� ��
      �����, � ������ ��� ����������.�������� ��
      ���������, ��� � ��� �� ����� ������ �������� ���
      ����������.

    5. iptables — ���� ������
      �������� ���������� �� iptables. � �����������
      ��������� ���������� ����� ������ ����� ����������,
      ������� ��������� ���� � iptables.

    6. Other — ����� �������������
      ������ ���������, ������� �� ��������� � � ������
      �� ������������� ��������.

  2. Module loading — ���� ������
    ��������� �������� ������ �������. ������ ����� ������
    ��������� ��������� ������, � �� ����� ��� ������ �����
    ������ ��������� ����������� ������.

    Note

    �������� ��������. ��������� ������,
    ���������� �� �������������� �����������, �����
    ���� ������� ���� ���� ��� �� ���������.
    ������, � ����� �������, ������ ��������
    �������� ��� �����������.

    1. Required modules — ����
      ������ ������ ��������� ������, ����������� ���
      ������ ��������.

    2. Non-required modules — ����
      ������ �������� ������, ������� �� ��������� ���
      ���������� ������ ��������. ��� ��� ������ ������
      ���� ����������������. ���� ��� ��� �����������, ��
      �� ������ ������ ����������������� ��.

  3. proc configuration — ���� ������
    �������� �� ��������� �������� ������� /proc. ���� ���
    ��������� ���������� — ��� ����� �����������, ���� ���,
    �� ��� ������ ���� ���������������� ��-���������, �
    ������� ��� ��-���������. ����������� �������� ��������
    /proc ����� ����������� � ��������, �� ������ ��
    ���.

    1. Required proc configuration
      — ���� ������ ������ ��������� ��� ���������
      ��������� ��������� ��� /proc. ��� ����� ����
      ��������� ��� ������� ������� ������, ��������,
      ��������� ����������� ����������� ���
      �������������� ��� �������������.

    2. Non-required proc
      configuration
      — ���� ������ ������ ���������
      ��-��������� ��������� /proc, ������� �����
      ��������� ��������� � �������. ��� ��� ������ ����
      ����������������, ��� ��� ��� ���������� ��
      ��������� ��� ������ ��������. ���� ������ �����
      ��������� ������ �� ��� ��������� /proc.

  4. rules set up — � ����� �������
    ������, ��� �������, ��� ����������� � ����, �����
    ��������� ������ ������. � ������ ��� ������� ��
    �������� � ��������. ����� ���������������� �������
    ������ ���� ������� ������, ��� �� ������ ��
    ������������. � �������� ������� � �� ������ ������ �
    ��� �� �������, � ����� ��� ��������� �������� iptables -L.

    1. Filter table — ������ �����
      �� �������� ������� filter. ��� ������ ����������
      ���������� �������� �� ��������� � �������.

      1. Set policies
        ���������� ������� ��-��������� ��� ���������
        �������. ������ � ������������ DROP ��� ������� �
        ������� filter, � ���� ���������� ������,
        ������� ���� �������. ��� ����� �� ��������� ��
        �����, ��� ��� ��������.

      2. Create user specified
        chains
        — � ���� �������, ��������� ���
        ���������������� �������, ������� �� �����
        ������������ ����� � �������� ���� �������. ��
        �� ������ ������������ ��� ������� � �� ���
        ���, ���� �� �������� ��.

      3. Create content in user
        specified chains
        — ����� ��������
        ���������������� �������, �� ����� ��������� ��
        ���������. ������������ �������, �� �������
        ������� ��� ���������������� �������
        ������������ ����� — ��� �������� � ��������,
        ��������� ��� �������. �� �� ������ ���������
        ������� � ������ ����� ������ ��������.

      4. INPUT chain — � ����
        ������� ����������� ������� ��� �������
        INPUT.

        Note

        ��� ��� �����������, � ��������
        ��������� �������, ������� ���������� �
        ������ ������� iptables -L.
        ��� ��������� ������, ����� ���������
        ��� ���������, ������, ��������
        �������� ���������� ������ �� ���������
        ������ � �������, ��� ��� ������
        ������� ������� ������ ����� �����
        ������ � ���������� ���������
        ��������.

      5. FORWARD chain — ����� ��
        ��������� ������� � ������� FORWARD

      6. OUTPUT chain — ����
        ��������� � ������� filter, ����������� �������
        OUTPUT.

    2. nat table — ����� �������
      filter �� ��������� � ������� nat. ������� ��� ��
      ���� ������. ������ ����� — �� ������� ���������
      �������� NAT �� ������ ������, ����� ��� ��������
      �������� ������� ��� ����������� (�� ����, �����
      NAT ��� ��������, �� ��� �� ������ �������
      ����������). �����, � ������������ ������� nat ���
      ������ ���� �������, ������� ��������� ��� �������
      filter. ������� filter �������� ������ ���� �����,
      � �� ����� ��� nat — �������� ������ ����, �
      ������� mangle. ����� ��������������� ��� ��������
      ������ ������� nat. ��� ����� ���� �� ������
      ���������, �� � �� ������ �� ����������������.

      1. Set policies — ������
        ����� �� ������������� ��� �������� ��
        ��������� � �������� ������� nat. ������, �
        ������������ ACCEPT. ��� ������� �� ������
        �������������� ��� ����������, � �� �� ������
        ����� «�����������» (DROP) ������.
        ���� ��� ���������� �������� �������� �������
        ����� ����� ���� � ����� ������� ��-�� �����
        �������������. � ��������� ��� ������ � ����
        ��������, ��������� �� ���� ������� ������ ��
        ������ �����.

      2. Create user specified
        chains
        — ����� ��������� ���
        ���������������� ������� ��� ������� nat.
        ������ � ���� �� ���, �� � ������� ���� ������
        �� ������ ������. �������� ��������, ���
        ���������������� ������� ������ ���� ������� ��
        �� ������������ �������������.

      3. Create content in user
        specified chains
        — ���������� ������ �
        ���������������� ������� ������� nat. �������
        ���������� ������ ����� ��� �� ��� � � �������
        filter. � �������� �� ����� ������, ��� �� ����
        ������ �������� �� � ������ �����.

      4. PREROUTING chain
        ������� PREROUTING ������������ ��� DNAT. �
        ����������� ��������� DNAT �� ������������, ���
        �� ������� ���� ����������������, ����� ��
        «��������� ������» � ���� ���������
        ���� ������� ������. � ��������� ��������� ���
        ������� ��������, ��� ��� ������������ ����
        ���� ��������� ������� � �������������� �����,
        ������� ��� DNAT ����������.

      5. POSTROUTING chain
        ������� POSTROUTING ������������ ����������,
        ������� � �������, ��� ��� � �����������
        ������� ������� ���� ��� ����� ��������� �����,
        ������� �� ����� ���������� � �������� �����
        ������� �����. ������� ������� �� �����
        ������������ SNAT, �� � ��������� �������, ��
        ��������� ����� ������������ MASQUERADE.

      6. OUTPUT chain — �������
        OUTPUT ������������ ������ � ����� ��
        ���������. �� � ���� �� ����� ���������
        ��������� ��� ������������� ���� �������. ����
        �� ����������� ��� �������, �������� ��� ����
        �����, � � ����� ��������������� ��������� �
        ������ �����������.

    3. mangle table — �������
      mangle — ��������� ������� �� ���� �������. ������
      � �� ��������� ��� ������� ������, ��� ��� ������
      �� ��������� ������������ � ��� ����, ����
      ��������� TTL ���� ��� ���� TOS � ��. �������
      �������, � ������� ���� ������ ������ � ���������
      ���������, � ����������� ������������, ��� �
      �������, ��������� �������� ������������� ����
      �������.

      1. Set policies — �����
        �������� �������� ��-���������. �����
        ���������� �� �� �����������, ��� � ��� �������
        nat. ������� �� ������ �������������� ���
        ����������, � ������������� �� ������ ��������
        �����. � �� ������������ ������� �������� �
        ����� �� ��������� ��� ������� � �������
        mangle, � ��� ������ ��������� ��� ��.

      2. Create user specified
        chains
        — ��������� ����������������
        �������. ��� ��� � �� ��������� ������� mangle
        � ���������, � �� ���� ���������
        ���������������� �������. ������, ���� ������
        ��� �������� �� ������ ������.

      3. Create content in user
        specified chains
        — ���� �� ������� �����
        ���� ���������������� ������� � �������� ����
        �������, �� ������ ��������� �� ���������
        �����.

      4. PREROUTING — � ����
        ������ ������� ������ ���������� � �������.

      5. INPUT chain — � ����
        ������ ������� ������ ���������� � �������.

      6. FORWARD chain — � ����
        ������ ������� ������ ���������� � �������.

      7. OUTPUT chain — � ����
        ������ ������� ������ ���������� � �������.

      8. POSTROUTING chain — �
        ���� ������ ������� ������ ���������� �
        �������.

�������, ��� � �������� ���������� ��������, ��� ������
�������� �������������� � ������ ��� ��������������� �����
��������.

Caution

�������� ��������, ��� ��� �������� �����������
������, � �������� ���� ������� ���������� ����,
������ �������� ����� ����� ���������. � ��
��������� �� ������ � ��������� ��������� � ��
���������, ��� ��� — ������������ � ������
�������.


8.2. rc.firewall.txt

�������� rc.firewall.txt — �������� ����, ��
������� ������������ ��������� ��������. ����� ���� rc.firewall
���������� �������� ��������� ��������. �������� ������� ���
�������� ����, ��� �� ������ ���� ��������� ���� � ����
����������� � Internet. ���� �������� ����� ������� ��
�������������, ��� �� ������ ����������� IP �����, �
������������� �� ����������� DHCP, PPP, SLIP ���� ����� �� ������ ��������,
������� ��������� IP �����������. � ��������� ������ ��������
�� ������ �������� rc.DHCP.firewall.txt

�������� �������, ����� ��������� ����� ����
�������������� ���� ����������, ���� ��� ������. ��� �����
���� �� ��� �������� ����� ���������������� ����� ����,
���������, ������� �� �������� ������� � ����� ��������,
����� ����������� ��������� �������������� ������������ �
���� ����.

  • CONFIG_NETFILTER

  • CONFIG_IP_NF_CONNTRACK

  • CONFIG_IP_NF_IPTABLES

  • CONFIG_IP_NF_MATCH_LIMIT

  • CONFIG_IP_NF_MATCH_STATE

  • CONFIG_IP_NF_FILTER

  • CONFIG_IP_NF_NAT

  • CONFIG_IP_NF_TARGET_LOG


8.3. rc.DMZ.firewall.txt

�������� rc.DMZ.firewall.txt ��� ������� ��� ���,
��� ����� ������������� ��������� ����, ����
«�������������������� ����» � ���� ����������� �
Internet. ��� ������� � �������� �������������������� ����, �
������ ������, �����, ������������ NAT «���� �
������», �� ����, �� ������ ��������� ����������
������������ ������ ����� ��� ��� ������ IP ������.

�������� �������, ����� ��������� ����� ����
�������������� ���� ����������, ���� ��� ������. ��� �����
���� �� ��� �������� ����� ����������������

  • CONFIG_NETFILTER

  • CONFIG_IP_NF_CONNTRACK

  • CONFIG_IP_NF_IPTABLES

  • CONFIG_IP_NF_MATCH_LIMIT

  • CONFIG_IP_NF_MATCH_STATE

  • CONFIG_IP_NF_FILTER

  • CONFIG_IP_NF_NAT

  • CONFIG_IP_NF_TARGET_LOG

�������� �������� � ����� ����������� ������, ��� ���
������������������ �� �������. ���� ���������� �������� IP
������� 192.168.0.0/24 � �������� ������������� ����������
�����. ������ ���������� �������� 192.168.1.0/24 � ����������
�������������������� ����� (DMZ), ��� ������� �� �����
��������� �������������� ������� (NAT) «���� �
������». ��������, ���� ���-�� �� �������� ��������
����� �� ��� DNS_IP, �� �� �������� DNAT ��� �������� ������ �� DNS � DMZ. ���� �� DNAT �� ����������, �� DNS �� ���� ��
�������� ������, ��������� �� ����� ����� DMZ_DNS_IP, � �� DNS_IP. ���������� �����������
��������� ��������:

$IPTABLES -t nat -A PREROUTING -p TCP -i $INET_IFACE -d $DNS_IP \
--dport 53 -j DNAT --to-destination $DMZ_DNS_IP
   

��� ������ �������, ��� DNAT ����� ����������� ������ �
������� PREROUTING ������� nat. �������� �����
�������, ����� ������ ��������� �� ��������� TCP �� $INET_IFACE � ��������� IP, �������
������������� ������ $DNS_IP, � ��������� �� ���� 53. ����
�������� ����� �����, �� ����������� ������� ������
����������, ��� DNAT. �������� DNAT ���������� ����� ��� ������� �
������� ����� —to-destination $DMZ_DNS_IP. �����
����� ���������� ������������ ����� ������, �� ������� �����
���� ����� ����������� ����� ������������� ������� � $DMZ_DNS_IP �� $DNS_IP, ������� ������� ��������
������������ ������� ����������� ������������� � �� �������
�������� �������������� ������.

������ �� ��� ������ �������� ��� �������� DNAT, ����� �������������� �����������
� ������ �������� ��� ����� ���� �������. ���� ���-�� ��� ���
�������� �� ����� � ��� �� ���� ����������� � ������
���������, �� �� ������ �������� ��� �� ���� — �������� ���
��� ������.


8.4. rc.DHCP.firewall.txt

�������� The rc.DHCP.firewall.txt ����� ����� ��
�������� rc.firewall.txt. ������,
���� �������� ������ �� ���������� ���������� STATIC_IP, ��� � �������� ��������
�������� �� ��������� rc.firewall.txt. ������� � ���, ���
rc.firewall.txt �� ����� �������� � ������ ������������� IP
������. ���������, �� ��������� � ���������� — ����������.
���� �������� ����� ������� � ������ DHCP, PPPSLIP ����������� � ��������.

�������� �������, ����� ��������� ����� ����
�������������� ���� ����������, ���� ��� ������. ��� �����
���� �� ��� �������� ����� ����������������

  • CONFIG_NETFILTER

  • CONFIG_IP_NF_CONNTRACK

  • CONFIG_IP_NF_IPTABLES

  • CONFIG_IP_NF_MATCH_LIMIT

  • CONFIG_IP_NF_MATCH_STATE

  • CONFIG_IP_NF_FILTER

  • CONFIG_IP_NF_NAT

  • CONFIG_IP_NF_TARGET_MASQUERADE

  • CONFIG_IP_NF_TARGET_LOG

������� ������� ������� ������� ������� � ��������
���������� STATIC_IP � ���� ������ �� ���
����������. ������ ��� ������ ������������ ���������� INET_IFACE. ������� ������� -d $STATIC_IP ���������� �� -i $INET_IFACE. ���������� ��� ���,
��� ����� �������� � ����������������. (������� ��������, ���
� ������ ������ ��� STATIC_IP ����� �������� ���������� INET_IP ����. �����.)

�� ������ �� ����� ������������� ������� � ������� INPUT �������� �����: —in-interface $LAN_IFACE —dst
$INET_IP
. ��� � ���� ������� ��������� ��� �������
������� ����������� ������ �� ������� ����������. ��������,
����� �� ����������� ������� HTTP ������. ���� �� �������� ��
������� ���������, ���������� ����������� ������ ������� ��
���� �� ������, ������� �������� ��� ������������ �������, ��
�� ����� «�������» ������ �������. ����, �������
�������� ����� NAT, �������� ����� DNS IP ����� HTTP �������,
����� ���� ��������� �������� ������ � ����� IP. ����
���������� ���������� ���������� �� ���������� � IP ������,
�� ���� �� ������ �������� �����, ��������� ������� INPUT ����������� ����� ������. ���
��� �� ����������� � ��� ��������� ������� ����� �� �����
����������� IP �����, �� ����� ��� ����� ������, ���������
�������, ������� ��������� ������, ���������� � LAN
���������� �� ��� INET_IP � ��������� ACCEPT ��� ���.

����� ����� ��������������, �� ����� �� ������ �����
���������� ����� � �������� ��������, ������� �� �����������
������������ IP. ��������, ����� ���� �� �������� ������,
������� �������� IP ����� ����� ifconfig � ����������� ��� � �����
�������� (��� ������������ ��������������� ����������),
������� «���������» ���������� � ��������.
������������� ���� linuxguruz.org ����� �������� ���������
��������, ��������� ��� ����������. ������ �� linuxguruz.org
�� ������� � ���������� ������ �� ������
�������
.

Note

���� �������� ����� ��������� ��� rc.firewall.txt. �
������������ ���������� ��� ������������ �������� rc.firewall.txt, ���� ���
��������, ��� ��� rc.DHCP.firewall.txt �����
������ ��� ��������� �����.

�����, ����� �������� � ���� �������� ��� ������ �����
�����:

INET_IP=`ifconfig $INET_IFACE | grep inet | cut -d : -f 2 | \
cut -d ' ' -f 1`
   

���� ����������� ������� �������� ������������ IP ��
����������. ����� ����������� ������ ��������� IP ������ ��
������� � �������� retreiveip.txt. ������ � ������ �������
���� ��������� ����������, ������� �������� ����.

  1. ���� ������ ����������� �� ������� ��������, ������� �
    ���� ������� ����������� ������� PPP, �� ��� �����
    �������� � «���������» ����, ��� �������������
    ����������, ��-�� ������, ������� ������������� ������ ��
    �������� NEW � �� ���������� ����� SYN. (������ ������ ������ �� �������� NEW � ��
    ���������� ����� SYN
    ). �������� ������� �����
    ��������� ��������� ���� ������, �� ����� �������
    �������� ����������� � ����� ������ ������������.

  2. �����������, ��� � ��� ���� ����� ����������� ������,
    �������� ����� ����� ��������� ������� � ���������
    �������, � ���� �� ������ ��������� ������������.

  3. ��� ����� �������� � �������� �����������, ��� � ����
    �������, ������ ���������� ������. ��� ����� ������, ���
    ����� ��� ������������.


8.5. rc.UTIN.firewall.txt

�������� rc.UTIN.firewall.txt, � ������� �� ������
���������, ��������� LAN, ������� ��������� �� ������������.
�� �������� ���������� ������������� �� ������ ���
������������� �� Internet. ������� �������, �� �� ��������
������, �� � ��������, �� � ��������� ����, � �������� ��
�������. ������� ������ � �������� �������������� ������
����������� POP3, HTTP � FTP.

���� �������� ������� �������� ������� — «�� �������
������, ���� ����������� ��������». ��� ������� �� ����
— ������� ����� ���� � �������, ������� ������������
��������, ������������ ��������� �������� �� ��������� �����.
���� ��������, �������, ���� ��������� ��������, �������
������� ��� ������� ���� ���������� ������. �� ����
���������� �� ��������� rc.firewall.txt, �� ��������
��������� � ���, ��� �� ������ ����������.

�������� �������, ����� ��������� ����� ����
�������������� ���� ����������, ���� ��� ������. ��� �����
���� �� ��� �������� ����� ����������������

  • CONFIG_NETFILTER

  • CONFIG_IP_NF_CONNTRACK

  • CONFIG_IP_NF_IPTABLES

  • CONFIG_IP_NF_MATCH_LIMIT

  • CONFIG_IP_NF_MATCH_STATE

  • CONFIG_IP_NF_FILTER

  • CONFIG_IP_NF_NAT

  • CONFIG_IP_NF_TARGET_LOG

This script follows the golden rule to not trust anyone,
not even our own employees. This is a sad fact, but a large
part of the hacks and cracks that a company gets hit by is a
matter of people from their own staff perpetrating the hit.
This script will hopefully give you some clues as to what you
can do with your firewall to strengthen it up. It’s not
very different from the original rc.firewall.txt script, but it does
give a few hints at what we would normally let through
etc.


8.6. rc.test-iptables.txt

�������� rc.test-iptables.txt ������������ ���
�������� ��������� ������� �� ����� �����������
�������������� ��������, � ����������� �� ����� ������������,
��������, ��������� ip_forwarding ��� ���������
masquerading � �.�. ��� �� ����� � ����������� ������� �
�������� �����������, ����� ��������� �������� �������, ����
�������� ����� ��������������. � ����������������, � ����
�������� ������������ ��������� �������� LOG �� ping-������� � ping-������.
����� �������� ���������� ����������� ������������� �
��������� ������� ����� ������� ����������� � � �����
�������. ��������� �������� � ����� ��������� ���������
�������:

ping -c 1 host.on.the.internet
   

� �� ����� ���������� ������ ������� ��������� tail -n 0 -f /var/log/messages.
������ �� ������ ���� ������ ��� ������������ ������� �
������� �� �����������.

Note

���� �������� ��� ������� ������������� �
���������������� �����. ������� �������, �� �������
����� ������� ��� �������������� ������� ����,
������� ������������ ��� ������ ��� �����������. �
��������� ������ �� �������� ����� ������ ������� ���
��������������, ������� ����� �������� ��� ��������,
«�������» ��� ���, ��� ����� �������
«����� � ������������», � ����� �����
������� � ��������� ������ ����� ������� �� �����
���� ������������, ��������� �� ������ ����
��������������� ��������.


8.7.
rc.flush-iptables.txt

�������� rc.flush-iptables.txt � ����������������
�� ����� ��������������� �������� ��������� �� ���������� ���
���� ������� � �������. � ������ ��������, ���������������
�������� ��-��������� ACCEPT ��� ������� INPUT, OUTPUTFORWARD � ������� filter. �����
����� ������������ � �������� ��-��������� �������� ���
������� PREROUTING, POSTROUTINGOUTPUT ������� nat. ��� ��������
����������� �������, ����� �� ��������� ������� � ���������
������������ � ������������ ��������. ����������, ����
�������� ����� �������������� ��� ���������� ����������� �
��������� � ��� ������� ����� ���������, ������� ����� ��
��������� ������ �� ������� ������ ������ � ��������� �������
��-���������.

����� ��������� ��������� ������� ��-���������, ��
��������� � ������� ����������� ������� � �������� filternat, � ����� ������������ ��������
����, ������������ �������������, �������. ����� ����� ������
������� �����������. ���� �� ����������� ������� mangle, �� �� ������ ������ �������� �
�������� ��������������� ������ ��� ��������� ����
�������.

Note

� ���������� ���� ����. ����� ������ ����������
����, � ������ �� �� ��������� ����� ����� �������� �
rc.firewal, ������� ��� ������ ���� rc.firewall start
��� ������� �������. � �� ������ ����� �� ��� ���,
������ ��� ������, ��� ������� �������� ������ �����
� ���� �������� ���� � �� ������ ���� ����������
�������������� ���������� �� �������� �����������.
���������� ������������ ���������� ������ ��������
����� ������������, � ��� ������� �������� �����
������� � ���������, ������� ������ �����������
�������� �����, ������ ��� ����, � ���������
���������� �����.


8.8. Limit-match.txt

�������� limit-match.txt ������� � �����
������������������ ������ � ��������� limit. ��������� ����
������ � ���������� ���������� �� ���� ���� ping-������ �
���������� �����������.


8.9. Pid-owner.txt

�������� pid-owner.txt ������������� �������������
�������� —pid-owner. ����������, ���� �������� ������ ��
���������, �������, ����� ������� ��� ��������, ���
����������� ��������������� �������� iptables -L -v.


8.10. Sid-owner.txt

�������� sid-owner.txt ������������� �������������
�������� —sid-owner. ����������, ���� �������� ������ ��
���������, �������, ����� ������� ��� ��������, ���
����������� ��������������� �������� iptables -L -v.


8.11. Ttl-inc.txt

��������� ������ ttl-inc.txt, ��������������� ��� �����
������� ����������/������ «���������» ���
��������������, �������� ��� ����� ������ ����������.


���������� A. ��������� ��������
����������� ������

A.1. ����� ������ ������

����� ������� ������ ������ ����� ��������� �������
iptables � ������ L, ������� ������
��� ������ ����� � ����� ��� ������� �������.
�������� ��� �������� ���:

iptables -L

��� ������� ������� �� ����� ������ ������ � �������������
����. ������ ������ ����� ������������� � ����� ����� �
������������ � ������ /etc/services, IP ������ �����
������������� � ����� ������ ����� ���������� ���� � ������
DNS. � ����������� (resolving) ����
����� ���������� ��������� ��������, ��������, ���� ����
192.168.0.0/16 ������ DNS �� ������ ���������� ��� ����� �
������� 192.168.1.1, � ���������� ���������� ����������
�������. ����� ������ ��� �������� ������� ��������� �����
������ ������ � �������������� ������:

iptables -L -n

����� ������� �������������� ���������� � �������� �
��������, ���������

iptables -L -n -v

�� ��������� � ����� -t, ������� ����� ���� �����������
��� ��������� ������ nat � mangle, ��������:

iptables -L -t nat

� �������� ������� /proc ������� ��� ������, �������
�������� ���������� ���������� ��� ��� ����������. ��������,
�������� ��� ���������� ����������� ������ ���������� �
������� conntrack. ��� �������� �������, ������� ��������
������ ������������ ���������� � � ����� ��������� ������ ��
��� ���������. ��� ��������� ������� ��������� �������

cat /proc/net/ip_conntrack |
less


A.2. ��������� � ������� �����
������

�� ���� ���� ��� �� ���������� ����������� � ������������
iptables, ����� ���� ��� ����������
����� �������� ������ �� �������� ��������� ������ �� �������
��� ������������� ������������ ������. ������ � �������� ��
���� ��������. ���� �� �� ������ �������� ����� ���� �������,
�� ��� ����� ������ �������� ������� -A �� ������� -D � ������ �������. iptables ������ �������� ������� �
������ ���. ���� ������� ��������� ������, ������� ��������
��� �������� ������ ��� ��������, �� ����� ������ ������ ��
��������� ������. ���� ����� ������� ����� ��� �� ����������,
�� ������� -D, � �������� ���������, �����
�������� ����� ��������� ������, ��������, ������� iptables -D INPUT 10 ������ �������
������� � ������� INPUT. (����� ������ ����� �������, �������
������� iptables -L ��������_�������
—line-numbers
, ����� ������� ����� ���������� ��
������ �������� ����. �����.)

��� �������� ����������� ����� ������� ����������� �������
-F. ��������: iptables -F INPUT — ������ ���
������� � ������� INPUT, ������ ��� ������� �� ��������
�������� ������� ��-���������, ��� ��� ���� ��� �����������
��� DROP �� ����� ������������� ���, ���
�������� � ������� INPUT. ����� �������� ��������
��-���������, ����� ������ ���������� �� � ��������������
���������, �������� iptables -P INPUT ACCEPT. (� ���: ���� ������� �� ������� ���� ������
-t (—table), �� ������� �������
������������ ������ � ������� filter, ����. �����. )

���� ��� ������� ��������� �������� (��������� ���������
����) ������� ���������� ������� ���� ������ � �������, �
����������������� �������� ������� � iptables. ���������, ��� ���
������������� ������� mangle ��� ���������� ������
���������� � ���� ��������, ��������� �� �� ��
������������.


���������� B. ����� �������� �
�������

B.1. �������� ��������
�������

�� ������ ����������� � ����������� ���������� ��� �������
��������� ��� ��� ���� ������. ��������, ����� ���� ������
��������� �� ���������� �������������� ������

insmod: iptable_filter: no module by that name found

���� ��� ��� ������ ��� ������������. ������ ��������, ���
������������� ������ (��� ������) ��� ������ � �����
����������. ��� ������, ��� �� ������ ���������. � �������,
����������� ����, ��������� ������ ��� �������� �������
filter. ����� ��������� ������� ���� ������� ������ ���������
�������:

iptables -t filter -L
  

���� ��� ���������, �� ��� ������� ������� ������ ����
������� �� ������� filter. ����� ������ ��������� ��������
���:

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
   

���� ������� filter �����������, �� ����� ����� ��������
���������

iptables v1.2.5: can't initialize iptables table `filter': Table \
     does not exist (do you need to insmod?)
Perhaps iptables or your kernel needs to be upgraded.
   

��� ��� ���������, ��� ��� ��� ��������� ��������� �� ��,
��� ���� �� ������ ���������� ������, ���� �� ������
��������� depmod -a, ���� �� ������ ��
�������������� ����������� ������ ��� ������� ������ ��������
��������� ������� make modules_install � �������� �
��������� �������� ����. ������ �������� �������� ��������
������� depmod -a. ���������� �������
�������� ��� ������� �� ����� ������� �����������, � � ����
������ ���������� �������� �������� ��������� The Linux Documentation Project.
(��������� ��� ��� � ������ ���������, ��� �����������
������� ��������� iptables. ����. �����.)

������ ������, ������� �� ������ �������� ��� �������
iptables:

iptables: No chain/target/match by that name
  

��� ������ ��������, ��� ��� ����� �������, �������� ���
��������. ��� ����� �������� �� ��������� ����� ��������,
�������� ��������, ��� �� ��������� ������������
�������������� (��� ��� �� ������������) �������,
�������������� �������� ��� ��������. ���� ������, ��� ��
�������� ����������� ������.


B.2. ������ �� �������� NEW � �� ����������
����� SYN

��� �������� iptables ������������ ������
�����������������, � ������� ������ ����� ������� ���
������������� �������� (������� � ����). ���� �� �����������
�������, ������������ ������ ������ NEW, �� �� ���������� ���������
���� SYN, �� ������ �� ���������� �����
SYN ������ «�����������»
����� ���� ������. ����, � ������, ����� �� ����������
��������� ������������, ����� ����� ����� ��������� ������
ESTABLISHED ����������,
�������������� ����� ������ ����������. ��������� ��������
������, �� ������ ��������� ���������� ������ ���� ��� �����
������������, ��� ���� �� ����� ����� �� ��� ���������� ��
����� ��������� ������������� ����������, ��������� �������
�� �������� ������ ��� �� ������� �� ���� ������ ����������.
������ ��� �������� ������������� ����������� ����� TCP
����������. �� ��������� ����� ������� �������� ���������
������� � ������� INPUT, OUTPUTFORWARD:

$IPTABLES -A INPUT -p tcp ! --syn -m state --state NEW -j LOG \
     --log-prefix "New not syn:"
$IPTABLES -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
   
Caution

��������������� ������� ����������� �� ����
��������. ������ ����������� ����������� ���
���������� ������ ����������� ������� �� ������
������� ������.

�������� ��������, ��� ������� ��������� ������������ �
���������������� ��������� � ������ ����������� TCP/IP ��
Microsoft. ���� � ���, ��� ��� ��������� ��������, ������,
��������������� ����������� �� Microsoft ����������� ���
NEW � �������� ���� �������� �����
��������. ���, ������, �� �������� � ���������� ����������,
��������� � ����. ���������� ��� ������, ���, �����
���������� �����������, � ���������� ����������� ����� FIN/ACK, �� netfilter ��������� ��� ���������� �
������� ��� �� ������� conntrack. � ���� ������, ���������
��� Microsoft �������� ������ �����, �������� �������������
������ NEW, �� � ���� ������ �� ����������
��� SYN �, ������������� �������������
�������������� ��������. ������ ������ — ����� �� �����������
�� ������ ���� ������. � ������ ���� — �� ������� �����������
��������� ������, ���� ���������� ������������� ������ (��.
������� ����) � ����������� � ����.

������� ��� ���� ��������� �������� � ����� ���������.
���� ���-�� � ��������� ����� ������ � ������������, ��������
�� LAN, � ���������� PPP, �� � ���� ������ ���������� �����
����������. ��� ���������� � ������, ����� ����������� ���
����������� conntracknat ������. ������ ������ �������� ���
�������� ������� � ���, ����� ��������� �������� rc.firewall.txt �� ������ telnet � ������� ����������. ��� �����
�� ������������ �� telnet � ������������. ���������� rc.firewall.txt, � �������� ����������
��������, ����������� ������ ����������� �����������,
�������� ������� «NEW not SYN». ����� ������ telnet ��� daemon ������� ������� ���
������, �� ��� ����������� ����� ���������� ��������������
����� ��� NEW, �� ������ �� �����
�������������� ���� SYN, ��� ��� ���, ����������,
�������� ������ ��� �������������� ����������. �������������,
����� ����� ��������������� �������� � ���������� ���� �����
�������������� � �������.


B.3. SYN/ACK — ������ � ������ ��
�������� NEW

���������� ���� �� �������������� �������-���� (�� ����.
spoofing — ������������, �������. ����. �����.), ������� ����������
«������������ ������ TCP-������������������»
(Sequence Number Prediction). ����� ���� ������ ����
����������� � ������������� ������ IP-������ ��� ��������� ��
����� ���� ���� ����.

��� ������������ �������� Sequence Number Prediction �����
��������� ����� [A] — ��������� ����, [V] — ��������� ����,
[O] — ������ ����, ��� IP-����� ������������ ���������.

  1. ���� [A] ���������� SYN-����� (������ �� ����������
    ����. �����.) ����� [V] �
    �������� IP-������� ����� [O].

  2. ���� [V] �������� ����� [O] ������� SYN/ACK.

  3. ������, �� ������ �����, ���� [O] ������ ���������
    ���������� ������� RST, ��������� �� �� ������� ������ ��
    ���������� (����� SYN) � ������� ����� ����������,
    ������, ��������, ��� ���� [O] �� ������� (��������
    �����������, ���������� ������� ��� ��������� ��
    ������������, ������� �� ��������� ����� SYN/ACK).

  4. ���� ���� [O] �� �������� ����� RST, ������� �����
    ������� ���������� �����, �� ��������� ���� [A] ��������
    ����������� �������������� � ������ [V], ������� ���� ��
    [O].

�� ������� RST-����� ��, ��� �����, ������������
���������� ����� �� ���� [V], ������� ����� ����
��������������� ��� �����. ������������ ���������
������������� ����������� ������ RST � �������� ������� (RST
� ����� �� ������������� SYN/ACK). ���� � ����� �����������
������������ �������, ����������� ������ �� �������� NEW �
���������� ����� SYN, �� SYN/ACK-������ �����
«������������» ����� ���������. �������, ���������
������� ���������� �������� � ������� bad_tcp_packets ������:

iptables -A bad_tcp_packets -p tcp --tcp-flags SYN,ACK SYN,ACK \
-m state --state NEW -j REJECT --reject-with tcp-reset
  

� ����������� ������� �������� ������� ������������
����������� ������� ������������ ��� ����� [O] � ���� �� ��
������������� ������������ �������. ���������� ����������
������ ������������� ����� ������������. � ���� ������
��������� ���������� ����� ��������� ����������������, ����
���� ��� ������ �������. ��� �������, �� ����� �������,
��������� ��������� ���� ������������ ������, �� �� �����
����.


B.4. ���������� ����� Internet,
������������ ����������������� IP-������

� ������� ���� ������ ����� ������������ ��� � ���������
����������� (Internet Service Providers), ������� ���������
IP ������, ���������� IANA ��� ��������� �����. ��������,
Swedish Internet Service Provider � ���������� ���������
Telia ���������� ����� ������ ��� ����� �������� DNS (�������� 10.x.x.x). ��������, �
������� �� ������ �������� �������� ������������, ������� �
���, ��� ��, � ����� ���������, ��������� ����������� � �����
IP � ��������� 10.x.x.x, ��-�� ����������� �������������
�������. ���� �� ����������� � ����� ���������, �� ��������
��� �������� ����� ����� ������. ��� ���������� �������,
������������ ������� � ���� ��������, ����� ������� INPUT, �������� ���:

/usr/local/sbin/iptables -t nat -I PREROUTING -i eth1 -s \
     10.0.0.1/32 -j ACCEPT
  

�������� �� ��������� �������� �����������, ��� ���
��������� ������� �� ������������� ��� ������������� �
��������. ��� ������������� ����� — ����������, ��� �����
����������� �������� ����� — ���������! �� �� �� ������
��������� ��� «�����������» �� ����� �������.


B.5. ��� ��������� �����������
DHCP �������� ����� iptables

� ����������������, ��� ������ ���������� ������, ���� ���
�������� �������� ������ ��������� DHCP. ������ ����� ���������� �����,
��� DHCP �������� �� ��������� UDP. �������������, �������� ��������
������ ���������. �����, ���������� �������� ���������,
��������, ���� DHCP ������� ���� ����� $LAN_IFACE, �� �������� �������� DHCP ������� ��������� ������ �����
���� ���������. � �������, ����� ������� ������� �����
������������, ������� �������� �����. DHCP ���������� ����� 67 � 68. �����
�������, ������� ������� ����� ��������� ���������
�������:

$IPTABLES  -I INPUT -i $LAN_IFACE -p udp --dport 67:68 --sport \
     67:68 -j ACCEPT
  

�������� ��������, ��� ������� ���������� ���� ������ ��
��������� UDP ����� ����� 67 � 68, ������ ��� ��
������ ��� �������� �������, ��������� ��� ��������� ����
�������� �������� �� ����� ����, ���������� ����������
���������� � ������� 67 � 68. ����� ������� ������
����������, ����� ��������� ���������� DHCP �������� � ��� ���� �� �������
������ «������� ������». ���� ��� ����� ���������
�������� ������������, �� �� ������ ������ ���������� ���
�������.


B.6. �������� mIRC DCC

mIRC ���������� ����������� ���������, ������� ���������
����������� ����� ���������� � ������������ DCC ����������
������� �������. ���� ��� ��������� ������������ ��������� �
iptables, ������ � �������� ip_conntrack_irc � ip_nat_irc, ��
��� ������ ������ �� ����� ��������. �������� ����������� �
���, ��� mIRC ������������� ��������� ���������� �������
������� (NAT) ������ �������. � ����������, ����� �����
�������� � iptables, ��� ������ �� �����, ��� � ��� ������.
mIRC �� �������, ��� ���������� ����� ���������
«�����», ����� ��������� ������������ IRC, �
������� �������������� ����������� ���� IP � ������� � �����
����������� ���, ��� �������� DCC �������.

��������� ����� «I am behind a firewall»
(«� �� ������������») � ������������� �������
ip_conntrack_irc � ip_nat_irc �������� � ����, ��� netfilter
����� � ��������� ������ ��������� «Forged DCC send
packet».

� ���� �������� ���� ������� ������� — ��������� ��� �����
� mIRC � ��������� iptables ��������� ��� ������.


���������� C. ���� ICMP

��� ������ ������ ����� ICMP ���������:

������� C-1. ICMP types

��� ��� �������� ������ ������
0 0 Echo Reply x
3 0 Network Unreachable x
3 1 Host Unreachable x
3 2 Protocol Unreachable x
3 3 Port Unreachable x
3 4 Fragmentation needed but no frag. bit
set
x
3 5 Source routing failed x
3 6 Destination network unknown x
3 7 Destination host unknown x
3 8 Source host isolated (obsolete) x
3 9 Destination network administratively
prohibited
x
3 10 Destination host administratively
prohibited
x
3 11 Network unreachable for TOS x
3 12 Host unreachable for TOS x
3 13 Communication administratively prohibited
by filtering
x
3 14 Host precedence violation x
3 15 Precedence cutoff in effect x
4 0 Source quench
5 0 Redirect for network
5 1 Redirect for host
5 2 Redirect for TOS and network
5 3 Redirect for TOS and host
8 0 Echo request x
9 0 Router advertisement
10 0 Route solicitation
11 0 TTL equals 0 during transit x
11 1 TTL equals 0 during reassembly x
12 0 IP header bad (catchall error) x
12 1 Required options missing x
13 0 Timestamp request (obsolete) x
14 Timestamp reply (obsolete) x
15 0 Information request (obsolete) x
16 0 Information reply (obsolete) x
17 0 Address mask request x
18 0 Address mask reply x


���������� D. ������ �� ������
�������

����� �������� ������ ������, ��� �� ������� ��������
�������������� ���������� :

  • ip-sysctl.txt — �� ������������ � ����
    2.4.14. ���������, �� ������� ���������� �� �����������
    �������� ���� ����.

  • ip_dynaddr.txt — �� ������������ � ����
    2.4.14. ��������� ���������� �� ���������� ���������
    ip_dynaddr, ��������� ����� sysctl � �������� �������
    /proc.

  • iptables.8 — ���� ��� iptables 1.2.4 �
    ������� HTML ���������� ����������� ��� �������� ������ �
    iptables. ������ ������� ����� ��� �����.

  • The Internet Control Message Protocol —
    ������� � ��������� ��������, ������������������� ICMP.
    ������� ������� �������� (Ralph Walden).

  • RFC 792 — Internet Control Message
    Protocol — ����������� �������� ���������� �� ���������
    ICMP. �������� ��� ����������� ���������� � ��������� ICMP,
    ������� ������ ����� �������������. ����� J. Postel.

  • RFC 793 — Transmission Control Protocol
    — ���� �������� ��������� �������� ��������� TCP. ��������
    ����������� ������� ������������ �������������, ������
    ������, �������� ������ ������ ��������� TCP �� ����
    �������, ������ ��������� ���� ��������. ����� J.
    Postel.

  • http://www.netfilter.org/ — �����������
    ���� netfilteriptables. ��������� ��� ����
    �������� ���������� iptablesnetfilter � linux.

  • Firewall rules table — ��������� ���� �
    ������� PDF, ������� ��������������� �������� �������
    (Stuart Clark), ������� ������������ �� ���� ����� �������
    ��� ������� ���������� �� ��������, ������������ ��
    �����������.

  • /etc/protocols — ������ �����
    protocols, ���������� � ������������ Slackware. �����
    ������� ������������ �� ������� ����������, ����� ��� IP,
    ICMP ��� TCP.

  • /etc/services — ������ �����
    services, ���������� � ������������ Slackware. �����������
    ������� ��� ���������, ����� ������� ����� ��������� �
    ������ ������� ��������.

  • Internet Engineering Task Force — ����
    �� ����� ������� �����, ������� ���������� ������������� �
    ���������� ���������� Internet. ������������ ����
    ����������� RFC. �������� � ���� ��� ������� ��������, ���
    � �������� ����, � ����� ����������� �����������������
    ���������.

  • Linux Advanced Routing and Traffic Control
    HOW-TO — ���� �� ������ ����������, ����������
    ��������. �������������� ���� ������ �������� (Bert
    Hubert).

  • Paksecured Linux Kernel patches — ��
    ����� �� ������� ��� «�������» � ����, ����������
    Matthew G. Marsh. ����� ����� �������, ����� �� �������
    «�������» FTOS.

  • ULOGD project page — �������� ��������
    ������� ULOGD.

  • The Linux Documentation Project ���� ��
    ������ ������, ���������� ������������. ����� �� �������
    �������� ���������� ���������� �� Linux-��������.

  • http://www.netfilter.org/documentation/index.html#FAQ
    — ����������� FAQ (Frequently Asked Questions) �� netfilter
    .

  • http://www.netfilter.org/unreliable-guides/packet-filtering-HOWTO/index.html
    — Rusty Russells Unreliable Guide to packet filtering.
    ���������� ������������ �� ������� ���������� ������� �
    ������� iptables, ���������� ����� �� �������������
    iptables � netfilter.

  • http://www.netfilter.org/unreliable-guides/NAT-HOWTO/index.html
    — Rusty Russells Unreliable Guide to Network Address
    Translation. ������������� ������������ �� Network Address
    Translation � iptables � netfilter, ���������� ����� ��
    �������� ������������� ����� �������� (Rusty Russell).

  • http://www.netfilter.org/unreliable-guides/netfilter-hacking-HOWTO/index.html
    — Rusty Russells Unreliable Netfilter Hacking HOWTO. ����
    �� �������� ���������� �� �������� ���� ��� ������ �
    netfilter � iptables. ��� �� ������� ����� �������� (Rusty
    Russell).

  • http://www.linuxguruz.org/iptables/ —
    �������� ��������� ������ � �������� �� ��������. �������
    ������ ��������� iptables ��� ��������� ����������.

  • http://www.islandsoft.net/veerapen.html
    — �������� ���������� �� ������������� ������ iptables,
    ��������: ���, ��������� �������������� ���������,
    ��������� ��� ��������� ������������� ���������
    «���������» ����� � ����������� ������ (banlist)
    � iptables.

  • http://kalamazoolinux.org/presentations/20010417/conntrack.html
    — ���������� �������� ������� ������������� ����������.
    ���� ��� ��������� ���� ����������� ����������, �� ���
    ������� ��� ���������.

  • http://www.docum.org — ���� �� ��������
    ������, ������� �������� ���������� � �������� Linux CBQ,
    tc � ip. ������������ ���� — Stef Coene.

  • http://lists.samba.org/mailman/listinfo/netfilter
    — ����������� ������ ������� (mailing-list) �� netfilter.
    ����������� ������� ��� ���������� �������� �� iptables �
    netfilter.

� ������� �� �������� ��� iptables, ������������ � ����,
������� �������� ���.


���������� E. �������������

� ����� �� �������� ������ ��������������� �����, �������
������� ��� ���������� ������ ��� �������� �����
���������.:

  • Fabrice Marie, ��� ��������
    ���������, �� ����������� ���� ������ ������. � ��� ��
    �������� ������� �� ������� ����� ��������� � ������
    DocBook.

  • Marc Boucher, �� ������ ��
    ��������� �������� ������ ��������� ����������� ���������
    �������.

  • Frode E. Nyboe, ��
    ������������������ ������ rc.firewall, �� ������������ ���� ��
    ������������� ������ � �� �������� ���������� ������ � ����
    �� ����.

  • Chapman Brad, Alexander W. Janssen, �� ������
    � ��������� ������� ����������� �������� �������� ������
    NAT � filter.

  • Michiel Brandenburg, Myles Uyema, �� ������ �
    �������� ��������������� ������, ������������ ��������
    �������� ��������� ������� (state matching).

  • Kent `Artech’ Stahre, ��
    ������ � ����������. � ����, ��� � ������ ����������, �
    Kent — ������ �� ���� ���� � ���� ;). � ��� �� ������� ��
    ����� ������ � ���� ���������.

  • Anders ‘DeZENT’ Johansson,
    �� ���������� � �������� ����������� (ISP), �������
    ���������� ������, ����������������� ��� ���������
    �����.

  • Jeremy `Spliffy’ Smith, ��
    �������������� ��������� � �� ������������ ���� ������.

� ������� �� ���� ���������, ��� ������� �� ��� �������,
���������� ���� �������� �� ���� ���������. ����� �������, ���
�� ���� ��������� ����.


���������� F. ����������

Version�1.1.19�(21�May�2003)
http://iptables-tutorial.frozentux.net
By:�Oskar�Andreasson
Contributors:�Peter�van�Kampen,�Xavier�Bartol,�Jon�Anderson,�Thorsten�Bremer

and�Spanish�Translation�Team.

Version�1.1.18�(24�Apr�2003)
http://iptables-tutorial.frozentux.net
By:�Oskar�Andreasson
Contributors:�Stuart�Clark,�Robert�P.�J.�Day,�Mark�Orenstein�and�Edmond�Shwayri.

Version�1.1.17�(6�Apr�2003)
http://iptables-tutorial.frozentux.net
By:�Oskar�Andreasson
Contributors:�Geraldo�Amaral�Filho,�Ondrej�Suchy,�Dino�Conti,�Robert�P.�J.�Day,

Velev�Dimo,�Spencer�Rouser,�Daveonos,�Amanda�Hickman,�Olle�Jonsson�and

Bengt�Aspvall.

Version�1.1.16�(16�Dec�2002)
�http://iptables-tutorial.frozentux.net
�By:�Oskar�Andreasson
�Contributors:�Clemens�Schwaighower,�Uwe�Dippel�and�Dave�Wreski.

Version�1.1.15�(13�Nov�2002)
http://iptables-tutorial.frozentux.net
By:�Oskar�Andreasson
Contributors:�Clemens�Schwaighower,�Uwe�Dippel�and�Dave�Wreski.

Version�1.1.15�(13�Nov�2002)
http://iptables-tutorial.frozentux.net
By:�Oskar�Andreasson
Contributors:�Mark�Sonarte,�A.�Lester�Buck,�Robert�P.�J.�Day,�Togan�Muftuoglu,

Antony�Stone,�Matthew�F.�Barnes�and�Otto�Matejka.�

Version�1.1.14�(14�Oct�2002)
http://iptables-tutorial.frozentux.net
By:�Oskar�Andreasson
Contributors:�Carol�Anne,�Manuel�Minzoni,�Yves�Soun,�Miernik,�Uwe�Dippel,�

Dave�Klipec�and�Eddy�L�O�Jansson.

Version�1.1.13�(22�Aug�2002)
http://iptables-tutorial.haringstad.com
By:�Oskar�Andreasson
Contributors:�Tons�of�people�reporting�bad�HTML�version.

Version�1.1.12�(19�Aug�2002)
http://www.netfilter.org/tutorial/
By:�Oskar�Andreasson
Contributors:�Peter�Schubnell,�Stephen�J.�Lawrence,�Uwe�Dippel,�Bradley�

Dilger,�Vegard�Engen,�Clifford�Kite,�Alessandro�Oliveira,�Tony�Earnshaw,�

Harald�Welte,�Nick�Andrew�and�Stepan�Kasal.

Version�1.1.11�(27�May�2002)
http://www.netfilter.org/tutorial/
By:�Oskar�Andreasson
Contributors:�Steve�Hnizdur,�Lonni�Friedman,�Jelle�Kalf,�Harald�Welte,�

Valentina�Barrios�and�Tony�Earnshaw.

Version�1.1.10�(12�April�2002)
http://www.boingworld.com/workshops/linux/iptables-tutorial/

By:�Oskar�Andreasson
Contributors:�Jelle�Kalf,�Theodore�Alexandrov,�Paul�Corbett,�Rodrigo�

Rubira�Branco,�Alistair�Tonner,�Matthew�G.�Marsh,�Uwe�Dippel,�Evan�

Nemerson�and�Marcel�J.E.�Mol.�

Version�1.1.9�(21�March�2002)
http://www.boingworld.com/workshops/linux/iptables-tutorial/

By:�Oskar�Andreasson
Contributors:�Vince�Herried,�Togan�Muftuoglu,�Galen�Johnson,�Kelly�Ashe,�Janne

Johansson,�Thomas�Smets,�Peter�Horst,�Mitch�Landers,�Neil�Jolly,�Jelle�Kalf,

Jason�Lam�and�Evan�Nemerson.

Version�1.1.8�(5�March�2002)
http://www.boingworld.com/workshops/linux/iptables-tutorial/

By:�Oskar�Andreasson

Version�1.1.7�(4�February�2002)
http://www.boingworld.com/workshops/linux/iptables-tutorial/

By:�Oskar�Andreasson
Contributors:�Parimi�Ravi,�Phil�Schultz,�Steven�McClintoc,�Bill�Dossett,

Dave�Wreski,�Erik�Sjilund,�Adam�Mansbridge,�Vasoo�Veerapen,�Aladdin�and

Rusty�Russell.

Version�1.1.6�(7�December�2001)
http://people.unix-fu.org/andreasson/
By:�Oskar�Andreasson
Contributors:�Jim�Ramsey,�Phil�Schultz,�Giran�B�ge,�Doug�Monroe,�Jasper

Aikema,�Kurt�Lieber,�Chris�Tallon,�Chris�Martin,�Jonas�Pasche,�Jan

Labanowski,�Rodrigo�R.�Branco,�Jacco�van�Koll�and�Dave�Wreski.

Version�1.1.5�(14�November�2001)
http://people.unix-fu.org/andreasson/
By:�Oskar�Andreasson
Contributors:�Fabrice�Marie,�Merijn�Schering�and�Kurt�Lieber.

Version�1.1.4�(6�November�2001)
http://people.unix-fu.org/andreasson
By:�Oskar�Andreasson
Contributors:�Stig�W.�Jensen,�Steve�Hnizdur,�Chris�Pluta�and�Kurt�Lieber.

Version�1.1.3�(9�October�2001)
http://people.unix-fu.org/andreasson
By:�Oskar�Andreasson
Contributors:�Joni�Chu,�N.Emile�Akabi-Davis�and�Jelle�Kalf.

Version�1.1.2�(29�September�2001)
http://people.unix-fu.org/andreasson
By:�Oskar�Andreasson

Version�1.1.1�(26�September�2001)
http://people.unix-fu.org/andreasson
By:�Oskar�Andreasson
Contributors:�Dave�Richardson.

Version�1.1.0�(15�September�2001)
http://people.unix-fu.org/andreasson
By:�Oskar�Andreasson

Version�1.0.9�(9�September�2001)
http://people.unix-fu.org/andreasson
By:�Oskar�Andreasson

Version�1.0.8�(7�September�2001)
http://people.unix-fu.org/andreasson
By:�Oskar�Andreasson

Version�1.0.7�(23�August�2001)
http://people.unix-fu.org/andreasson
By:�Oskar�Andreasson
Contributors:�Fabrice�Marie.

Version�1.0.6
http://people.unix-fu.org/andreasson
By:�Oskar�Andreasson

Version�1.0.5
http://people.unix-fu.org/andreasson
By:�Oskar�Andreasson
Contributors:�Fabrice�Marie.
���


���������� G. GNU Free Documentation
License

Version 1.1, March 2000

Copyright (C) 2000 Free Software Foundation, Inc. 59
Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone
is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.


0. PREAMBLE

The purpose of this License is to make a manual, textbook,
or other written document «free» in the sense of
freedom: to assure everyone the effective freedom to copy and
redistribute it, with or without modifying it, either
commercially or noncommercially. Secondarily, this License
preserves for the author and publisher a way to get credit
for their work, while not being considered responsible for
modifications made by others.

This License is a kind of «copyleft», which
means that derivative works of the document must themselves
be free in the same sense. It complements the GNU General
Public License, which is a copyleft license designed for free
software.

We have designed this License in order to use it for
manuals for free software, because free software needs free
documentation: a free program should come with manuals
providing the same freedoms that the software does. But this
License is not limited to software manuals; it can be used
for any textual work, regardless of subject matter or whether
it is published as a printed book. We recommend this License
principally for works whose purpose is instruction or
reference.


1. APPLICABILITY AND
DEFINITIONS

This License applies to any manual or other work that
contains a notice placed by the copyright holder saying it
can be distributed under the terms of this License. The
«Document», below, refers to any such manual or
work. Any member of the public is a licensee, and is
addressed as «you».

A «Modified Version» of the Document means any
work containing the Document or a portion of it, either
copied verbatim, or with modifications and/or translated into
another language.

A «Secondary Section» is a named appendix or a
front-matter section of the Document that deals exclusively
with the relationship of the publishers or authors of the
Document to the Document’s overall subject (or to related
matters) and contains nothing that could fall directly within
that overall subject. (For example, if the Document is in
part a textbook of mathematics, a Secondary Section may not
explain any mathematics.) The relationship could be a matter
of historical connection with the subject or with related
matters, or of legal, commercial, philosophical, ethical or
political position regarding them.

The «Invariant Sections» are certain Secondary
Sections whose titles are designated, as being those of
Invariant Sections, in the notice that says that the Document
is released under this License.

The «Cover Texts» are certain short passages of
text that are listed, as Front-Cover Texts or Back-Cover
Texts, in the notice that says that the Document is released
under this License.

A «Transparent» copy of the Document means a
machine-readable copy, represented in a format whose
specification is available to the general public, whose
contents can be viewed and edited directly and
straightforwardly with generic text editors or (for images
composed of pixels) generic paint programs or (for drawings)
some widely available drawing editor, and that is suitable
for input to text formatters or for automatic translation to
a variety of formats suitable for input to text formatters. A
copy made in an otherwise Transparent file format whose
markup has been designed to thwart or discourage subsequent
modification by readers is not Transparent. A copy that is
not «Transparent» is called «Opaque».

Examples of suitable formats for Transparent copies
include plain ASCII without markup, Texinfo input format,
LaTeX input format, SGML or XML using a publicly available
DTD, and standard-conforming simple HTML designed for human
modification. Opaque formats include PostScript, PDF,
proprietary formats that can be read and edited only by
proprietary word processors, SGML or XML for which the DTD
and/or processing tools are not generally available, and the
machine-generated HTML produced by some word processors for
output purposes only.

The «Title Page» means, for a printed book, the
title page itself, plus such following pages as are needed to
hold, legibly, the material this License requires to appear
in the title page. For works in formats which do not have any
title page as such, «Title Page» means the text
near the most prominent appearance of the work’s title,
preceding the beginning of the body of the text.


2. VERBATIM COPYING

You may copy and distribute the Document in any medium,
either commercially or noncommercially, provided that this
License, the copyright notices, and the license notice saying
this License applies to the Document are reproduced in all
copies, and that you add no other conditions whatsoever to
those of this License. You may not use technical measures to
obstruct or control the reading or further copying of the
copies you make or distribute. However, you may accept
compensation in exchange for copies. If you distribute a
large enough number of copies you must also follow the
conditions in section 3.

You may also lend copies, under the same conditions stated
above, and you may publicly display copies.


3. COPYING IN QUANTITY

If you publish printed copies of the Document numbering
more than 100, and the Document’s license notice requires
Cover Texts, you must enclose the copies in covers that
carry, clearly and legibly, all these Cover Texts:
Front-Cover Texts on the front cover, and Back-Cover Texts on
the back cover. Both covers must also clearly and legibly
identify you as the publisher of these copies. The front
cover must present the full title with all words of the title
equally prominent and visible. You may add other material on
the covers in addition. Copying with changes limited to the
covers, as long as they preserve the title of the Document
and satisfy these conditions, can be treated as verbatim
copying in other respects.

If the required texts for either cover are too voluminous
to fit legibly, you should put the first ones listed (as many
as fit reasonably) on the actual cover, and continue the rest
onto adjacent pages.

If you publish or distribute Opaque copies of the Document
numbering more than 100, you must either include a
machine-readable Transparent copy along with each Opaque
copy, or state in or with each Opaque copy a
publicly-accessible computer-network location containing a
complete Transparent copy of the Document, free of added
material, which the general network-using public has access
to download anonymously at no charge using public-standard
network protocols. If you use the latter option, you must
take reasonably prudent steps, when you begin distribution of
Opaque copies in quantity, to ensure that this Transparent
copy will remain thus accessible at the stated location until
at least one year after the last time you distribute an
Opaque copy (directly or through your agents or retailers) of
that edition to the public.

It is requested, but not required, that you contact the
authors of the Document well before redistributing any large
number of copies, to give them a chance to provide you with
an updated version of the Document.


4. MODIFICATIONS

You may copy and distribute a Modified Version of the
Document under the conditions of sections 2 and 3 above,
provided that you release the Modified Version under
precisely this License, with the Modified Version filling the
role of the Document, thus licensing distribution and
modification of the Modified Version to whoever possesses a
copy of it. In addition, you must do these things in the
Modified Version:

  1. Use in the Title Page (and on the covers, if any) a
    title distinct from that of the Document, and from those
    of previous versions (which should, if there were any, be
    listed in the History section of the Document). You may
    use the same title as a previous version if the original
    publisher of that version gives permission.

  2. List on the Title Page, as authors, one or more
    persons or entities responsible for authorship of the
    modifications in the Modified Version, together with at
    least five of the principal authors of the Document (all
    of its principal authors, if it has less than five).

  3. State on the Title page the name of the publisher of
    the Modified Version, as the publisher.

  4. Preserve all the copyright notices of the
    Document.

  5. Add an appropriate copyright notice for your
    modifications adjacent to the other copyright
    notices.

  6. Include, immediately after the copyright notices, a
    license notice giving the public permission to use the
    Modified Version under the terms of this License, in the
    form shown in the Addendum below.

  7. Preserve in that license notice the full lists of
    Invariant Sections and required Cover Texts given in the
    Document’s license notice.

  8. Include an unaltered copy of this License.

  9. Preserve the section entitled «History», and
    its title, and add to it an item stating at least the
    title, year, new authors, and publisher of the Modified
    Version as given on the Title Page. If there is no
    section entitled «History» in the Document,
    create one stating the title, year, authors, and
    publisher of the Document as given on its Title Page,
    then add an item describing the Modified Version as
    stated in the previous sentence.

  10. Preserve the network location, if any, given in the
    Document for public access to a Transparent copy of the
    Document, and likewise the network locations given in the
    Document for previous versions it was based on. These may
    be placed in the «History» section. You may
    omit a network location for a work that was published at
    least four years before the Document itself, or if the
    original publisher of the version it refers to gives
    permission.

  11. In any section entitled «Acknowledgements»
    or «Dedications», preserve the section’s
    title, and preserve in the section all the substance and
    tone of each of the contributor acknowledgements and/or
    dedications given therein.

  12. Preserve all the Invariant Sections of the Document,
    unaltered in their text and in their titles. Section
    numbers or the equivalent are not considered part of the
    section titles.

  13. Delete any section entitled «Endorsements».
    Such a section may not be included in the Modified
    Version.

  14. Do not retitle any existing section as
    «Endorsements» or to conflict in title with any
    Invariant Section.

If the Modified Version includes new front-matter sections
or appendices that qualify as Secondary Sections and contain
no material copied from the Document, you may at your option
designate some or all of these sections as invariant. To do
this, add their titles to the list of Invariant Sections in
the Modified Version’s license notice. These titles must
be distinct from any other section titles.

You may add a section entitled «Endorsements»,
provided it contains nothing but endorsements of your
Modified Version by various parties—for example, statements
of peer review or that the text has been approved by an
organization as the authoritative definition of a
standard.

You may add a passage of up to five words as a Front-Cover
Text, and a passage of up to 25 words as a Back-Cover Text,
to the end of the list of Cover Texts in the Modified
Version. Only one passage of Front-Cover Text and one of
Back-Cover Text may be added by (or through arrangements made
by) any one entity. If the Document already includes a cover
text for the same cover, previously added by you or by
arrangement made by the same entity you are acting on behalf
of, you may not add another; but you may replace the old one,
on explicit permission from the previous publisher that added
the old one.

The author(s) and publisher(s) of the Document do not by
this License give permission to use their names for publicity
for or to assert or imply endorsement of any Modified
Version.


5. COMBINING DOCUMENTS

You may combine the Document with other documents released
under this License, under the terms defined in section 4
above for modified versions, provided that you include in the
combination all of the Invariant Sections of all of the
original documents, unmodified, and list them all as
Invariant Sections of your combined work in its license
notice.

The combined work need only contain one copy of this
License, and multiple identical Invariant Sections may be
replaced with a single copy. If there are multiple Invariant
Sections with the same name but different contents, make the
title of each such section unique by adding at the end of it,
in parentheses, the name of the original author or publisher
of that section if known, or else a unique number. Make the
same adjustment to the section titles in the list of
Invariant Sections in the license notice of the combined
work.

In the combination, you must combine any sections entitled
«History» in the various original documents,
forming one section entitled «History»; likewise
combine any sections entitled «Acknowledgements»,
and any sections entitled «Dedications». You must
delete all sections entitled «Endorsements.»


6. COLLECTIONS OF
DOCUMENTS

You may make a collection consisting of the Document and
other documents released under this License, and replace the
individual copies of this License in the various documents
with a single copy that is included in the collection,
provided that you follow the rules of this License for
verbatim copying of each of the documents in all other
respects.

You may extract a single document from such a collection,
and distribute it individually under this License, provided
you insert a copy of this License into the extracted
document, and follow this License in all other respects
regarding verbatim copying of that document.


7. AGGREGATION WITH INDEPENDENT
WORKS

A compilation of the Document or its derivatives with
other separate and independent documents or works, in or on a
volume of a storage or distribution medium, does not as a
whole count as a Modified Version of the Document, provided
no compilation copyright is claimed for the compilation. Such
a compilation is called an «aggregate», and this
License does not apply to the other self-contained works thus
compiled with the Document, on account of their being thus
compiled, if they are not themselves derivative works of the
Document.

If the Cover Text requirement of section 3 is applicable
to these copies of the Document, then if the Document is less
than one quarter of the entire aggregate, the Document’s
Cover Texts may be placed on covers that surround only the
Document within the aggregate. Otherwise they must appear on
covers around the whole aggregate.


8. TRANSLATION

Translation is considered a kind of modification, so you
may distribute translations of the Document under the terms
of section 4. Replacing Invariant Sections with translations
requires special permission from their copyright holders, but
you may include translations of some or all Invariant
Sections in addition to the original versions of these
Invariant Sections. You may include a translation of this
License provided that you also include the original English
version of this License. In case of a disagreement between
the translation and the original English version of this
License, the original English version will prevail.


9. TERMINATION

You may not copy, modify, sublicense, or distribute the
Document except as expressly provided for under this License.
Any other attempt to copy, modify, sublicense or distribute
the Document is void, and will automatically terminate your
rights under this License. However, parties who have received
copies, or rights, from you under this License will not have
their licenses terminated so long as such parties remain in
full compliance.


10. FUTURE REVISIONS OF THIS
LICENSE

The Free Software Foundation may publish new, revised
versions of the GNU Free Documentation License from time to
time. Such new versions will be similar in spirit to the
present version, but may differ in detail to address new
problems or concerns. See http://www.gnu.org/copyleft/.

Each version of the License is given a distinguishing
version number. If the Document specifies that a particular
numbered version of this License «or any later
version» applies to it, you have the option of following
the terms and conditions either of that specified version or
of any later version that has been published (not as a draft)
by the Free Software Foundation. If the Document does not
specify a version number of this License, you may choose any
version ever published (not as a draft) by the Free Software
Foundation.


How to use this License for your
documents

To use this License in a document you have written,
include a copy of the License in the document and put the
following copyright and license notices just after the title
page:

Copyright (c) YEAR YOUR NAME. Permission is granted to
copy, distribute and/or modify this document under the
terms of the GNU Free Documentation License, Version 1.1 or
any later version published by the Free Software
Foundation; with the Invariant Sections being LIST THEIR
TITLES, with the Front-Cover Texts being LIST, and with the
Back-Cover Texts being LIST. A copy of the license is
included in the section entitled «GNU Free
Documentation License».

If you have no Invariant Sections, write «with no
Invariant Sections» instead of saying which ones are
invariant. If you have no Front-Cover Texts, write «no
Front-Cover Texts» instead of «Front-Cover Texts
being LIST»; likewise for Back-Cover Texts.

If your document contains nontrivial examples of program
code, we recommend releasing these examples in parallel under
your choice of free software license, such as the GNU General
Public License, to permit their use in free software.


���������� H. GNU General Public License

Version 2, June 1991

Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59
Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone
is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.


0. Preamble

The licenses for most software are designed to take away
your freedom to share and change it. By contrast, the GNU
General Public License is intended to guarantee your freedom
to share and change free software—to make sure the software
is free for all its users. This General Public License
applies to most of the Free Software Foundation’s
software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is
covered by the GNU Library General Public License instead.)
You can apply it to your programs, too.

When we speak of free software, we are referring to
freedom, not price. Our General Public Licenses are designed
to make sure that you have the freedom to distribute copies
of free software (and charge for this service if you wish),
that you receive source code or can get it if you want it,
that you can change the software or use pieces of it in new
free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that
forbid anyone to deny you these rights or to ask you to
surrender the rights. These restrictions translate to certain
responsibilities for you if you distribute copies of the
software, or if you modify it.

For example, if you distribute copies of such a program,
whether gratis or for a fee, you must give the recipients all
the rights that you have. You must make sure that they, too,
receive or can get the source code. And you must show them
these terms so they know their rights.

We protect your rights with two steps: (1) copyright the
software, and (2) offer you this license which gives you
legal permission to copy, distribute and/or modify the
software.

Also, for each author’s protection and ours, we want
to make certain that everyone understands that there is no
warranty for this free software. If the software is modified
by someone else and passed on, we want its recipients to know
that what they have is not the original, so that any problems
introduced by others will not reflect on the original
authors’ reputations.

Finally, any free program is threatened constantly by
software patents. We wish to avoid the danger that
redistributors of a free program will individually obtain
patent licenses, in effect making the program proprietary. To
prevent this, we have made it clear that any patent must be
licensed for everyone’s free use or not licensed at
all.

The precise terms and conditions for copying, distribution
and modification follow.


1. TERMS AND CONDITIONS FOR
COPYING, DISTRIBUTION AND MODIFICATION

  1. This License applies to any program or other work
    which contains a notice placed by the copyright holder
    saying it may be distributed under the terms of this
    General Public License. The «Program», below,
    refers to any such program or work, and a «work
    based on the Program» means either the Program or
    any derivative work under copyright law: that is to say,
    a work containing the Program or a portion of it, either
    verbatim or with modifications and/or translated into
    another language. (Hereinafter, translation is included
    without limitation in the term «modification».)
    Each licensee is addressed as «you».

    Activities other than copying, distribution and
    modification are not covered by this License; they are
    outside its scope. The act of running the Program is not
    restricted, and the output from the Program is covered
    only if its contents constitute a work based on the
    Program (independent of having been made by running the
    Program). Whether that is true depends on what the
    Program does.

  2. You may copy and distribute verbatim copies of the
    Program’s source code as you receive it, in any
    medium, provided that you conspicuously and appropriately
    publish on each copy an appropriate copyright notice and
    disclaimer of warranty; keep intact all the notices that
    refer to this License and to the absence of any warranty;
    and give any other recipients of the Program a copy of
    this License along with the Program.

    You may charge a fee for the physical act of
    transferring a copy, and you may at your option offer
    warranty protection in exchange for a fee.

  3. You may modify your copy or copies of the Program or
    any portion of it, thus forming a work based on the
    Program, and copy and distribute such modifications or
    work under the terms of Section 1 above, provided that
    you also meet all of these conditions:

    1. You must cause the modified files to carry
      prominent notices stating that you changed the files
      and the date of any change.

    2. You must cause any work that you distribute or
      publish, that in whole or in part contains or is
      derived from the Program or any part thereof, to be
      licensed as a whole at no charge to all third parties
      under the terms of this License.

    3. If the modified program normally reads commands
      interactively when run, you must cause it, when
      started running for such interactive use in the most
      ordinary way, to print or display an announcement
      including an appropriate copyright notice and a
      notice that there is no warranty (or else, saying
      that you provide a warranty) and that users may
      redistribute the program under these conditions, and
      telling the user how to view a copy of this License.
      (Exception: if the Program itself is interactive but
      does not normally print such an announcement, your
      work based on the Program is not required to print an
      announcement.)

    These requirements apply to the modified work as a
    whole. If identifiable sections of that work are not
    derived from the Program, and can be reasonably
    considered independent and separate works in themselves,
    then this License, and its terms, do not apply to those
    sections when you distribute them as separate works. But
    when you distribute the same sections as part of a whole
    which is a work based on the Program, the distribution of
    the whole must be on the terms of this License, whose
    permissions for other licensees extend to the entire
    whole, and thus to each and every part regardless of who
    wrote it.

    Thus, it is not the intent of this section to claim
    rights or contest your rights to work written entirely by
    you; rather, the intent is to exercise the right to
    control the distribution of derivative or collective
    works based on the Program.

    In addition, mere aggregation of another work not
    based on the Program with the Program (or with a work
    based on the Program) on a volume of a storage or
    distribution medium does not bring the other work under
    the scope of this License.

  4. You may copy and distribute the Program (or a work
    based on it, under Section 2) in object code or
    executable form under the terms of Sections 1 and 2 above
    provided that you also do one of the following:

    1. Accompany it with the complete corresponding
      machine-readable source code, which must be
      distributed under the terms of Sections 1 and 2 above
      on a medium customarily used for software
      interchange; or,

    2. Accompany it with a written offer, valid for at
      least three years, to give any third party, for a
      charge no more than your cost of physically
      performing source distribution, a complete
      machine-readable copy of the corresponding source
      code, to be distributed under the terms of Sections 1
      and 2 above on a medium customarily used for software
      interchange; or,

    3. Accompany it with the information you received as
      to the offer to distribute corresponding source code.
      (This alternative is allowed only for noncommercial
      distribution and only if you received the program in
      object code or executable form with such an offer, in
      accord with Subsection b above.)

    The source code for a work means the preferred form of
    the work for making modifications to it. For an
    executable work, complete source code means all the
    source code for all modules it contains, plus any
    associated interface definition files, plus the scripts
    used to control compilation and installation of the
    executable. However, as a special exception, the source
    code distributed need not include anything that is
    normally distributed (in either source or binary form)
    with the major components (compiler, kernel, and so on)
    of the operating system on which the executable runs,
    unless that component itself accompanies the
    executable.

    If distribution of executable or object code is made
    by offering access to copy from a designated place, then
    offering equivalent access to copy the source code from
    the same place counts as distribution of the source code,
    even though third parties are not compelled to copy the
    source along with the object code.

  5. You may not copy, modify, sublicense, or distribute
    the Program except as expressly provided under this
    License. Any attempt otherwise to copy, modify,
    sublicense or distribute the Program is void, and will
    automatically terminate your rights under this License.
    However, parties who have received copies, or rights,
    from you under this License will not have their licenses
    terminated so long as such parties remain in full
    compliance.

  6. You are not required to accept this License, since you
    have not signed it. However, nothing else grants you
    permission to modify or distribute the Program or its
    derivative works. These actions are prohibited by law if
    you do not accept this License. Therefore, by modifying
    or distributing the Program (or any work based on the
    Program), you indicate your acceptance of this License to
    do so, and all its terms and conditions for copying,
    distributing or modifying the Program or works based on
    it.

  7. Each time you redistribute the Program (or any work
    based on the Program), the recipient automatically
    receives a license from the original licensor to copy,
    distribute or modify the Program subject to these terms
    and conditions. You may not impose any further
    restrictions on the recipients’ exercise of the
    rights granted herein. You are not responsible for
    enforcing compliance by third parties to this
    License.

  8. If, as a consequence of a court judgment or allegation
    of patent infringement or for any other reason (not
    limited to patent issues), conditions are imposed on you
    (whether by court order, agreement or otherwise) that
    contradict the conditions of this License, they do not
    excuse you from the conditions of this License. If you
    cannot distribute so as to satisfy simultaneously your
    obligations under this License and any other pertinent
    obligations, then as a consequence you may not distribute
    the Program at all. For example, if a patent license
    would not permit royalty-free redistribution of the
    Program by all those who receive copies directly or
    indirectly through you, then the only way you could
    satisfy both it and this License would be to refrain
    entirely from distribution of the Program.

    If any portion of this section is held invalid or
    unenforceable under any particular circumstance, the
    balance of the section is intended to apply and the
    section as a whole is intended to apply in other
    circumstances.

    It is not the purpose of this section to induce you to
    infringe any patents or other property right claims or to
    contest validity of any such claims; this section has the
    sole purpose of protecting the integrity of the free
    software distribution system, which is implemented by
    public license practices. Many people have made generous
    contributions to the wide range of software distributed
    through that system in reliance on consistent application
    of that system; it is up to the author/donor to decide if
    he or she is willing to distribute software through any
    other system and a licensee cannot impose that
    choice.

    This section is intended to make thoroughly clear what
    is believed to be a consequence of the rest of this
    License.

    If the distribution and/or use of the Program is
    restricted in certain countries either by patents or by
    copyrighted interfaces, the original copyright holder who
    places the Program under this License may add an explicit
    geographical distribution limitation excluding those
    countries, so that distribution is permitted only in or
    among countries not thus excluded. In such case, this
    License incorporates the limitation as if written in the
    body of this License.

  9. The Free Software Foundation may publish revised
    and/or new versions of the General Public License from
    time to time. Such new versions will be similar in spirit
    to the present version, but may differ in detail to
    address new problems or concerns.

    Each version is given a distinguishing version number.
    If the Program specifies a version number of this License
    which applies to it and «any later version»,
    you have the option of following the terms and conditions
    either of that version or of any later version published
    by the Free Software Foundation. If the Program does not
    specify a version number of this License, you may choose
    any version ever published by the Free Software
    Foundation.

  10. If you wish to incorporate parts of the Program into
    other free programs whose distribution conditions are
    different, write to the author to ask for permission. For
    software which is copyrighted by the Free Software
    Foundation, write to the Free Software Foundation; we
    sometimes make exceptions for this. Our decision will be
    guided by the two goals of preserving the free status of
    all derivatives of our free software and of promoting the
    sharing and reuse of software generally.

  11. NO WARRANTY

    BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE
    IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED
    BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN
    WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
    PROVIDE THE PROGRAM «AS IS» WITHOUT WARRANTY OF
    ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
    FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO
    THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.
    SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST
    OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR
    AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY
    OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE
    PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
    INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
    CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY
    TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
    DATA OR DATA BEING RENDERED INACCURATE OR LOSSES
    SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE
    PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH
    HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY
    OF SUCH DAMAGES.

END OF TERMS AND CONDITIONS


2. How to Apply These Terms to Your New
Programs

If you develop a new program, and you want it to be of the
greatest possible use to the public, the best way to achieve
this is to make it free software which everyone can
redistribute and change under these terms.

To do so, attach the following notices to the program. It
is safest to attach them to the start of each source file to
most effectively convey the exclusion of warranty; and each
file should have at least the «copyright» line and
a pointer to where the full notice is found.

<one�line�to�give�the�program’s�name�and�a�brief�idea�of�what�it�does.>

Copyright�(C)�<year>��<name�of�author>
����

This program is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public
License as published by the Free Software Foundation;
either version 2 of the License, or (at your option) any
later version.

This program is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU General Public License for more
details.

You should have received a copy of the GNU General
Public License along with this program; if not, write to
the Free Software Foundation, Inc., 59 Temple Place, Suite
330, Boston, MA 02111-1307 USA

Also add information on how to contact you by electronic
and paper mail.

If the program is interactive, make it output a short
notice like this when it starts in an interactive mode:

Gnomovision version 69, Copyright (C) year name of
author Gnomovision comes with ABSOLUTELY NO WARRANTY; for
details type `show w’. This is free software, and you
are welcome to redistribute it under certain conditions;
type `show c’ for details.

The hypothetical commands `show w’ and `show c’
should show the appropriate parts of the General Public
License. Of course, the commands you use may be called
something other than `show w’ and `show c’; they
could even be mouse-clicks or menu items—whatever suits your
program.

You should also get your employer (if you work as a
programmer) or your school, if any, to sign a «copyright
disclaimer» for the program, if necessary. Here is a
sample; alter the names:

Yoyodyne,�Inc.,�hereby�disclaims�all�copyright�interest�in�the�program

`Gnomovision’�(which�makes�passes�at�compilers)�written�by�James�Hacker.

��

<signature�of�Ty�Coon>,�1�April�1989
Ty�Coon,�President�of�Vice
��

This General Public License does not permit incorporating
your program into proprietary programs. If your program is a
subroutine library, you may consider it more useful to permit
linking proprietary applications with the library. If this is
what you want to do, use the GNU Library General Public
License instead of this License.


���������� I. ������� ���������

I.1. ������ rc.firewall

#!/bin/sh
#
# rc.firewall - Initial SIMPLE IP Firewall script for Linux 2.4.x and iptables
#
# Copyright (C) 2001  Oskar Andreasson <bluefluxATkoffeinDOTnet>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program or from the site that you downloaded it
# from; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307   USA
#

###########################################################################
#
# 1. Configuration options.
#

#
# 1.1 Internet Configuration.
#

INET_IP="194.236.50.155"
INET_IFACE="eth0"
INET_BROADCAST="194.236.50.255"

#
# 1.1.1 DHCP
#

#
# 1.1.2 PPPoE
#

#
# 1.2 Local Area Network configuration.
#
# your LAN's IP range and localhost IP. /24 means to only use the first 24
# bits of the 32 bit IP address. the same as netmask 255.255.255.0
#

LAN_IP="192.168.0.2"
LAN_IP_RANGE="192.168.0.0/16"
LAN_IFACE="eth1"

#
# 1.3 DMZ Configuration.
#

#
# 1.4 Localhost Configuration.
#

LO_IFACE="lo"
LO_IP="127.0.0.1"

#
# 1.5 IPTables Configuration.
#

IPTABLES="/usr/sbin/iptables"

#
# 1.6 Other Configuration.
#

###########################################################################
#
# 2. Module loading.
#

#
# Needed to initially load modules
#

/sbin/depmod -a

#
# 2.1 Required modules
#

/sbin/modprobe ip_tables
/sbin/modprobe ip_conntrack
/sbin/modprobe iptable_filter
/sbin/modprobe iptable_mangle
/sbin/modprobe iptable_nat
/sbin/modprobe ipt_LOG
/sbin/modprobe ipt_limit
/sbin/modprobe ipt_state

#
# 2.2 Non-Required modules
#

#/sbin/modprobe ipt_owner
#/sbin/modprobe ipt_REJECT
#/sbin/modprobe ipt_MASQUERADE
#/sbin/modprobe ip_conntrack_ftp
#/sbin/modprobe ip_conntrack_irc
#/sbin/modprobe ip_nat_ftp
#/sbin/modprobe ip_nat_irc

###########################################################################
#
# 3. /proc set up.
#

#
# 3.1 Required proc configuration
#

echo "1" > /proc/sys/net/ipv4/ip_forward

#
# 3.2 Non-Required proc configuration
#

#echo "1" > /proc/sys/net/ipv4/conf/all/rp_filter
#echo "1" > /proc/sys/net/ipv4/conf/all/proxy_arp
#echo "1" > /proc/sys/net/ipv4/ip_dynaddr

###########################################################################
#
# 4. rules set up.
#

######
# 4.1 Filter table
#

#
# 4.1.1 Set policies
#

$IPTABLES -P INPUT DROP
$IPTABLES -P OUTPUT DROP
$IPTABLES -P FORWARD DROP

#
# 4.1.2 Create userspecified chains
#

#
# Create chain for bad tcp packets
#

$IPTABLES -N bad_tcp_packets

#
# Create separate chains for ICMP, TCP and UDP to traverse
#

$IPTABLES -N allowed
$IPTABLES -N tcp_packets
$IPTABLES -N udp_packets
$IPTABLES -N icmp_packets

#
# 4.1.3 Create content in userspecified chains
#

#
# bad_tcp_packets chain
#

$IPTABLES -A bad_tcp_packets -p tcp --tcp-flags SYN,ACK SYN,ACK \
-m state --state NEW -j REJECT --reject-with tcp-reset 
$IPTABLES -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j LOG \
--log-prefix "New not syn:"
$IPTABLES -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j DROP

#
# allowed chain
#

$IPTABLES -A allowed -p TCP --syn -j ACCEPT
$IPTABLES -A allowed -p TCP -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPTABLES -A allowed -p TCP -j DROP

#
# TCP rules
#

$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 21 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 22 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 80 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 113 -j allowed

#
# UDP ports
#

#$IPTABLES -A udp_packets -p UDP -s 0/0 --destination-port 53 -j ACCEPT
#$IPTABLES -A udp_packets -p UDP -s 0/0 --destination-port 123 -j ACCEPT
$IPTABLES -A udp_packets -p UDP -s 0/0 --destination-port 2074 -j ACCEPT
$IPTABLES -A udp_packets -p UDP -s 0/0 --destination-port 4000 -j ACCEPT

#
# In Microsoft Networks you will be swamped by broadcasts. These lines 
# will prevent them from showing up in the logs.
#

#$IPTABLES -A udp_packets -p UDP -i $INET_IFACE -d $INET_BROADCAST \
#--destination-port 135:139 -j DROP

#
# If we get DHCP requests from the Outside of our network, our logs will 
# be swamped as well. This rule will block them from getting logged.
#

#$IPTABLES -A udp_packets -p UDP -i $INET_IFACE -d 255.255.255.255 \
#--destination-port 67:68 -j DROP

#
# ICMP rules
#

$IPTABLES -A icmp_packets -p ICMP -s 0/0 --icmp-type 8 -j ACCEPT
$IPTABLES -A icmp_packets -p ICMP -s 0/0 --icmp-type 11 -j ACCEPT

#
# 4.1.4 INPUT chain
#

#
# Bad TCP packets we don't want.
#

$IPTABLES -A INPUT -p tcp -j bad_tcp_packets

#
# Rules for special networks not part of the Internet
#

$IPTABLES -A INPUT -p ALL -i $LAN_IFACE -s $LAN_IP_RANGE -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $LO_IFACE -s $LO_IP -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $LO_IFACE -s $LAN_IP -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $LO_IFACE -s $INET_IP -j ACCEPT

#
# Special rule for DHCP requests from LAN, which are not caught properly
# otherwise.
#

$IPTABLES -A INPUT -p UDP -i $LAN_IFACE --dport 67 --sport 68 -j ACCEPT

#
# Rules for incoming packets from the internet.
#

$IPTABLES -A INPUT -p ALL -d $INET_IP -m state --state ESTABLISHED,RELATED \
-j ACCEPT
$IPTABLES -A INPUT -p TCP -i $INET_IFACE -j tcp_packets
$IPTABLES -A INPUT -p UDP -i $INET_IFACE -j udp_packets
$IPTABLES -A INPUT -p ICMP -i $INET_IFACE -j icmp_packets

#
# If you have a Microsoft Network on the outside of your firewall, you may 
# also get flooded by Multicasts. We drop them so we do not get flooded by 
# logs
#

#$IPTABLES -A INPUT -i $INET_IFACE -d 224.0.0.0/8 -j DROP

#
# Log weird packets that don't match the above.
#

$IPTABLES -A INPUT -m limit --limit 3/minute --limit-burst 3 -j LOG \
--log-level DEBUG --log-prefix "IPT INPUT packet died: "

#
# 4.1.5 FORWARD chain
#

#
# Bad TCP packets we don't want
#

$IPTABLES -A FORWARD -p tcp -j bad_tcp_packets

#
# Accept the packets we actually want to forward
#

$IPTABLES -A FORWARD -i $LAN_IFACE -j ACCEPT
$IPTABLES -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

#
# Log weird packets that don't match the above.
#

$IPTABLES -A FORWARD -m limit --limit 3/minute --limit-burst 3 -j LOG \
--log-level DEBUG --log-prefix "IPT FORWARD packet died: "

#
# 4.1.6 OUTPUT chain
#

#
# Bad TCP packets we don't want.
#

$IPTABLES -A OUTPUT -p tcp -j bad_tcp_packets

#
# Special OUTPUT rules to decide which IP's to allow.
#

$IPTABLES -A OUTPUT -p ALL -s $LO_IP -j ACCEPT
$IPTABLES -A OUTPUT -p ALL -s $LAN_IP -j ACCEPT
$IPTABLES -A OUTPUT -p ALL -s $INET_IP -j ACCEPT

#
# Log weird packets that don't match the above.
#

$IPTABLES -A OUTPUT -m limit --limit 3/minute --limit-burst 3 -j LOG \
--log-level DEBUG --log-prefix "IPT OUTPUT packet died: "

######
# 4.2 nat table
#

#
# 4.2.1 Set policies
#

#
# 4.2.2 Create user specified chains
#

#
# 4.2.3 Create content in user specified chains
#

#
# 4.2.4 PREROUTING chain
#

#
# 4.2.5 POSTROUTING chain
#

#
# Enable simple IP Forwarding and Network Address Translation
#

$IPTABLES -t nat -A POSTROUTING -o $INET_IFACE -j SNAT --to-source $INET_IP

#
# 4.2.6 OUTPUT chain
#

######
# 4.3 mangle table
#

#
# 4.3.1 Set policies
#

#
# 4.3.2 Create user specified chains
#

#
# 4.3.3 Create content in user specified chains
#

#
# 4.3.4 PREROUTING chain
#

#
# 4.3.5 INPUT chain
#

#
# 4.3.6 FORWARD chain
#

#
# 4.3.7 OUTPUT chain
#

#
# 4.3.8 POSTROUTING chain
#

   


I.2. ������
rc.DMZ.firewall

#!/bin/sh
#
# rc.DMZ.firewall - DMZ IP Firewall script for Linux 2.4.x and iptables
#
# Copyright (C) 2001  Oskar Andreasson <bluefluxATkoffeinDOTnet>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program or from the site that you downloaded it
# from; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307   USA
#

###########################################################################
#
# 1. Configuration options.
#

#
# 1.1 Internet Configuration.
#

INET_IP="194.236.50.152"
HTTP_IP="194.236.50.153"
DNS_IP="194.236.50.154"
INET_IFACE="eth0"

#
# 1.1.1 DHCP
#

#
# 1.1.2 PPPoE
#

#
# 1.2 Local Area Network configuration.
#
# your LAN's IP range and localhost IP. /24 means to only use the first 24
# bits of the 32 bit IP address. the same as netmask 255.255.255.0
#

LAN_IP="192.168.0.1"
LAN_IFACE="eth1"

#
# 1.3 DMZ Configuration.
#

DMZ_HTTP_IP="192.168.1.2"
DMZ_DNS_IP="192.168.1.3"
DMZ_IP="192.168.1.1"
DMZ_IFACE="eth2"

#
# 1.4 Localhost Configuration.
#

LO_IFACE="lo"
LO_IP="127.0.0.1"

#
# 1.5 IPTables Configuration.
#

IPTABLES="/usr/sbin/iptables"

#
# 1.6 Other Configuration.
#

###########################################################################
#
# 2. Module loading.
#

#
# Needed to initially load modules
#
/sbin/depmod -a



#
# 2.1 Required modules
#

/sbin/modprobe ip_tables
/sbin/modprobe ip_conntrack
/sbin/modprobe iptable_filter
/sbin/modprobe iptable_mangle
/sbin/modprobe iptable_nat
/sbin/modprobe ipt_LOG
/sbin/modprobe ipt_limit
/sbin/modprobe ipt_state

#
# 2.2 Non-Required modules
#

#/sbin/modprobe ipt_owner
#/sbin/modprobe ipt_REJECT
#/sbin/modprobe ipt_MASQUERADE
#/sbin/modprobe ip_conntrack_ftp
#/sbin/modprobe ip_conntrack_irc
#/sbin/modprobe ip_nat_ftp
#/sbin/modprobe ip_nat_irc

###########################################################################
#
# 3. /proc set up.
#

#
# 3.1 Required proc configuration
#

echo "1" > /proc/sys/net/ipv4/ip_forward

#
# 3.2 Non-Required proc configuration
#

#echo "1" > /proc/sys/net/ipv4/conf/all/rp_filter
#echo "1" > /proc/sys/net/ipv4/conf/all/proxy_arp
#echo "1" > /proc/sys/net/ipv4/ip_dynaddr

###########################################################################
#
# 4. rules set up.
#

######
# 4.1 Filter table
#

#
# 4.1.1 Set policies
#

$IPTABLES -P INPUT DROP
$IPTABLES -P OUTPUT DROP
$IPTABLES -P FORWARD DROP

#
# 4.1.2 Create userspecified chains
#

#
# Create chain for bad tcp packets
#

$IPTABLES -N bad_tcp_packets

#
# Create separate chains for ICMP, TCP and UDP to traverse
#

$IPTABLES -N allowed
$IPTABLES -N icmp_packets

#
# 4.1.3 Create content in userspecified chains
#

#
# bad_tcp_packets chain
#

$IPTABLES -A bad_tcp_packets -p tcp --tcp-flags SYN,ACK SYN,ACK \
-m state --state NEW -j REJECT --reject-with tcp-reset
$IPTABLES -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j LOG \
--log-prefix "New not syn:"
$IPTABLES -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j DROP

#
# allowed chain
#

$IPTABLES -A allowed -p TCP --syn -j ACCEPT
$IPTABLES -A allowed -p TCP -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPTABLES -A allowed -p TCP -j DROP

#
# ICMP rules
#

# Changed rules totally
$IPTABLES -A icmp_packets -p ICMP -s 0/0 --icmp-type 8 -j ACCEPT
$IPTABLES -A icmp_packets -p ICMP -s 0/0 --icmp-type 11 -j ACCEPT

#
# 4.1.4 INPUT chain
#

#
# Bad TCP packets we don't want
#

$IPTABLES -A INPUT -p tcp -j bad_tcp_packets

#
# Packets from the Internet to this box
#

$IPTABLES -A INPUT -p ICMP -i $INET_IFACE -j icmp_packets

#
# Packets from LAN, DMZ or LOCALHOST
#

#
# From DMZ Interface to DMZ firewall IP
#

$IPTABLES -A INPUT -p ALL -i $DMZ_IFACE -d $DMZ_IP -j ACCEPT

#
# From LAN Interface to LAN firewall IP
#

$IPTABLES -A INPUT -p ALL -i $LAN_IFACE -d $LAN_IP -j ACCEPT

#
# From Localhost interface to Localhost IP's
#

$IPTABLES -A INPUT -p ALL -i $LO_IFACE -s $LO_IP -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $LO_IFACE -s $LAN_IP -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $LO_IFACE -s $INET_IP -j ACCEPT

#
# Special rule for DHCP requests from LAN, which are not caught properly
# otherwise.
#

$IPTABLES -A INPUT -p UDP -i $LAN_IFACE --dport 67 --sport 68 -j ACCEPT

#
# All established and related packets incoming from the internet to the
# firewall
#

$IPTABLES -A INPUT -p ALL -d $INET_IP -m state --state ESTABLISHED,RELATED \
-j ACCEPT

#
# In Microsoft Networks you will be swamped by broadcasts. These lines
# will prevent them from showing up in the logs.
#

#$IPTABLES -A INPUT -p UDP -i $INET_IFACE -d $INET_BROADCAST \
#--destination-port 135:139 -j DROP

#
# If we get DHCP requests from the Outside of our network, our logs will
# be swamped as well. This rule will block them from getting logged.
#

#$IPTABLES -A INPUT -p UDP -i $INET_IFACE -d 255.255.255.255 \
#--destination-port 67:68 -j DROP

#
# If you have a Microsoft Network on the outside of your firewall, you may
# also get flooded by Multicasts. We drop them so we do not get flooded by
# logs
#

#$IPTABLES -A INPUT -i $INET_IFACE -d 224.0.0.0/8 -j DROP

#
# Log weird packets that don't match the above.
#

$IPTABLES -A INPUT -m limit --limit 3/minute --limit-burst 3 -j LOG \
--log-level DEBUG --log-prefix "IPT INPUT packet died: "

#
# 4.1.5 FORWARD chain
#

#
# Bad TCP packets we don't want
#

$IPTABLES -A FORWARD -p tcp -j bad_tcp_packets


#
# DMZ section
#
# General rules
#

$IPTABLES -A FORWARD -i $DMZ_IFACE -o $INET_IFACE -j ACCEPT
$IPTABLES -A FORWARD -i $INET_IFACE -o $DMZ_IFACE -m state \
--state ESTABLISHED,RELATED -j ACCEPT
$IPTABLES -A FORWARD -i $LAN_IFACE -o $DMZ_IFACE -j ACCEPT
$IPTABLES -A FORWARD -i $DMZ_IFACE -o $LAN_IFACE -m state \
--state ESTABLISHED,RELATED -j ACCEPT

#
# HTTP server
#

$IPTABLES -A FORWARD -p TCP -i $INET_IFACE -o $DMZ_IFACE -d $DMZ_HTTP_IP \
--dport 80 -j allowed
$IPTABLES -A FORWARD -p ICMP -i $INET_IFACE -o $DMZ_IFACE -d $DMZ_HTTP_IP \
-j icmp_packets

#
# DNS server
#

$IPTABLES -A FORWARD -p TCP -i $INET_IFACE -o $DMZ_IFACE -d $DMZ_DNS_IP \
--dport 53 -j allowed
$IPTABLES -A FORWARD -p UDP -i $INET_IFACE -o $DMZ_IFACE -d $DMZ_DNS_IP \
--dport 53 -j ACCEPT
$IPTABLES -A FORWARD -p ICMP -i $INET_IFACE -o $DMZ_IFACE -d $DMZ_DNS_IP \
-j icmp_packets

#
# LAN section
#

$IPTABLES -A FORWARD -i $LAN_IFACE -j ACCEPT
$IPTABLES -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

#
# Log weird packets that don't match the above.
#

$IPTABLES -A FORWARD -m limit --limit 3/minute --limit-burst 3 -j LOG \
--log-level DEBUG --log-prefix "IPT FORWARD packet died: "

#
# 4.1.6 OUTPUT chain
#

#
# Bad TCP packets we don't want.
#

$IPTABLES -A OUTPUT -p tcp -j bad_tcp_packets

#
# Special OUTPUT rules to decide which IP's to allow.
#

$IPTABLES -A OUTPUT -p ALL -s $LO_IP -j ACCEPT
$IPTABLES -A OUTPUT -p ALL -s $LAN_IP -j ACCEPT
$IPTABLES -A OUTPUT -p ALL -s $INET_IP -j ACCEPT

#
# Log weird packets that don't match the above.
#

$IPTABLES -A OUTPUT -m limit --limit 3/minute --limit-burst 3 -j LOG \
--log-level DEBUG --log-prefix "IPT OUTPUT packet died: "

######
# 4.2 nat table
#

#
# 4.2.1 Set policies
#

#
# 4.2.2 Create user specified chains
#

#
# 4.2.3 Create content in user specified chains
#

#
# 4.2.4 PREROUTING chain
#

$IPTABLES -t nat -A PREROUTING -p TCP -i $INET_IFACE -d $HTTP_IP --dport 80 \
-j DNAT --to-destination $DMZ_HTTP_IP
$IPTABLES -t nat -A PREROUTING -p TCP -i $INET_IFACE -d $DNS_IP --dport 53 \
-j DNAT --to-destination $DMZ_DNS_IP
$IPTABLES -t nat -A PREROUTING -p UDP -i $INET_IFACE -d $DNS_IP --dport 53 \
-j DNAT --to-destination $DMZ_DNS_IP

#
# 4.2.5 POSTROUTING chain
#

#
# Enable simple IP Forwarding and Network Address Translation
#

$IPTABLES -t nat -A POSTROUTING -o $INET_IFACE -j SNAT --to-source $INET_IP

#
# 4.2.6 OUTPUT chain
#

######
# 4.3 mangle table
#

#
# 4.3.1 Set policies
#

#
# 4.3.2 Create user specified chains
#

#
# 4.3.3 Create content in user specified chains
#

#
# 4.3.4 PREROUTING chain
#

#
# 4.3.5 INPUT chain
#

#
# 4.3.6 FORWARD chain
#

#
# 4.3.7 OUTPUT chain
#

#
# 4.3.8 POSTROUTING chain
#

   


I.3. ������
rc.UTIN.firewall

#!/bin/sh
#
# rc.firewall - UTIN Firewall script for Linux 2.4.x and iptables
#
# Copyright (C) 2001  Oskar Andreasson <bluefluxATkoffeinDOTnet>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program or from the site that you downloaded it
# from; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307   USA
#

###########################################################################
#
# 1. Configuration options.
#

#
# 1.1 Internet Configuration.
#

INET_IP="194.236.50.155"
INET_IFACE="eth0"
INET_BROADCAST="194.236.50.255"

#
# 1.1.1 DHCP
#

#
# 1.1.2 PPPoE
#

#
# 1.2 Local Area Network configuration.
#
# your LAN's IP range and localhost IP. /24 means to only use the first 24
# bits of the 32 bit IP address. the same as netmask 255.255.255.0
#

LAN_IP="192.168.0.2"
LAN_IP_RANGE="192.168.0.0/16"
LAN_IFACE="eth1"

#
# 1.3 DMZ Configuration.
#

#
# 1.4 Localhost Configuration.
#

LO_IFACE="lo"
LO_IP="127.0.0.1"

#
# 1.5 IPTables Configuration.
#

IPTABLES="/usr/sbin/iptables"

#
# 1.6 Other Configuration.
#

###########################################################################
#
# 2. Module loading.
#

#
# Needed to initially load modules
#

/sbin/depmod -a

#
# 2.1 Required modules
#

/sbin/modprobe ip_tables
/sbin/modprobe ip_conntrack
/sbin/modprobe iptable_filter
/sbin/modprobe iptable_mangle
/sbin/modprobe iptable_nat
/sbin/modprobe ipt_LOG
/sbin/modprobe ipt_limit
/sbin/modprobe ipt_state

#
# 2.2 Non-Required modules
#

#/sbin/modprobe ipt_owner
#/sbin/modprobe ipt_REJECT
#/sbin/modprobe ipt_MASQUERADE
#/sbin/modprobe ip_conntrack_ftp
#/sbin/modprobe ip_conntrack_irc
#/sbin/modprobe ip_nat_ftp
#/sbin/modprobe ip_nat_irc

###########################################################################
#
# 3. /proc set up.
#

#
# 3.1 Required proc configuration
#

echo "1" > /proc/sys/net/ipv4/ip_forward

#
# 3.2 Non-Required proc configuration
#

#echo "1" > /proc/sys/net/ipv4/conf/all/rp_filter
#echo "1" > /proc/sys/net/ipv4/conf/all/proxy_arp
#echo "1" > /proc/sys/net/ipv4/ip_dynaddr

###########################################################################
#
# 4. rules set up.
#

######
# 4.1 Filter table
#

#
# 4.1.1 Set policies
#

$IPTABLES -P INPUT DROP
$IPTABLES -P OUTPUT DROP
$IPTABLES -P FORWARD DROP

#
# 4.1.2 Create userspecified chains
#

#
# Create chain for bad tcp packets
#

$IPTABLES -N bad_tcp_packets

#
# Create separate chains for ICMP, TCP and UDP to traverse
#

$IPTABLES -N allowed
$IPTABLES -N tcp_packets
$IPTABLES -N udp_packets
$IPTABLES -N icmp_packets

#
# 4.1.3 Create content in userspecified chains
#

#
# bad_tcp_packets chain
#

$IPTABLES -A bad_tcp_packets -p tcp --tcp-flags SYN,ACK SYN,ACK \
-m state --state NEW -j REJECT --reject-with tcp-reset
$IPTABLES -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j LOG \
--log-prefix "New not syn:"
$IPTABLES -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j DROP

#
# allowed chain
#

$IPTABLES -A allowed -p TCP --syn -j ACCEPT
$IPTABLES -A allowed -p TCP -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPTABLES -A allowed -p TCP -j DROP

#
# TCP rules
#

$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 21 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 22 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 80 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 113 -j allowed

#
# UDP ports
#

#$IPTABLES -A udp_packets -p UDP -s 0/0 --source-port 53 -j ACCEPT
#$IPTABLES -A udp_packets -p UDP -s 0/0 --source-port 123 -j ACCEPT
$IPTABLES -A udp_packets -p UDP -s 0/0 --source-port 2074 -j ACCEPT
$IPTABLES -A udp_packets -p UDP -s 0/0 --source-port 4000 -j ACCEPT

#
# In Microsoft Networks you will be swamped by broadcasts. These lines
# will prevent them from showing up in the logs.
#

#$IPTABLES -A udp_packets -p UDP -i $INET_IFACE -d $INET_BROADCAST \
#--destination-port 135:139 -j DROP

#
# If we get DHCP requests from the Outside of our network, our logs will
# be swamped as well. This rule will block them from getting logged.
#

#$IPTABLES -A udp_packets -p UDP -i $INET_IFACE -d 255.255.255.255 \
#--destination-port 67:68 -j DROP

#
# ICMP rules
#

$IPTABLES -A icmp_packets -p ICMP -s 0/0 --icmp-type 8 -j ACCEPT
$IPTABLES -A icmp_packets -p ICMP -s 0/0 --icmp-type 11 -j ACCEPT

#
# 4.1.4 INPUT chain
#

#
# Bad TCP packets we don't want.
#

$IPTABLES -A INPUT -p tcp -j bad_tcp_packets

#
# Rules for special networks not part of the Internet
#

$IPTABLES -A INPUT -p ALL -i $LO_IFACE -s $LO_IP -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $LO_IFACE -s $LAN_IP -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $LO_IFACE -s $INET_IP -j ACCEPT

#
# Rules for incoming packets from anywhere.
#

$IPTABLES -A INPUT -p ALL -d $INET_IP -m state --state ESTABLISHED,RELATED \
-j ACCEPT
$IPTABLES -A INPUT -p TCP -j tcp_packets
$IPTABLES -A INPUT -p UDP -j udp_packets
$IPTABLES -A INPUT -p ICMP -j icmp_packets

#
# If you have a Microsoft Network on the outside of your firewall, you may
# also get flooded by Multicasts. We drop them so we do not get flooded by
# logs
#

#$IPTABLES -A INPUT -i $INET_IFACE -d 224.0.0.0/8 -j DROP

#
# Log weird packets that don't match the above.
#

$IPTABLES -A INPUT -m limit --limit 3/minute --limit-burst 3 -j LOG \
--log-level DEBUG --log-prefix "IPT INPUT packet died: "

#
# 4.1.5 FORWARD chain
#

#
# Bad TCP packets we don't want
#

$IPTABLES -A FORWARD -p tcp -j bad_tcp_packets

#
# Accept the packets we actually want to forward
#

$IPTABLES -A FORWARD -p tcp --dport 21 -i $LAN_IFACE -j ACCEPT
$IPTABLES -A FORWARD -p tcp --dport 80 -i $LAN_IFACE -j ACCEPT
$IPTABLES -A FORWARD -p tcp --dport 110 -i $LAN_IFACE -j ACCEPT
$IPTABLES -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

#
# Log weird packets that don't match the above.
#

$IPTABLES -A FORWARD -m limit --limit 3/minute --limit-burst 3 -j LOG \
--log-level DEBUG --log-prefix "IPT FORWARD packet died: "

#
# 4.1.6 OUTPUT chain
#

#
# Bad TCP packets we don't want.
#

$IPTABLES -A OUTPUT -p tcp -j bad_tcp_packets

#
# Special OUTPUT rules to decide which IP's to allow.
#

$IPTABLES -A OUTPUT -p ALL -s $LO_IP -j ACCEPT
$IPTABLES -A OUTPUT -p ALL -s $LAN_IP -j ACCEPT
$IPTABLES -A OUTPUT -p ALL -s $INET_IP -j ACCEPT

#
# Log weird packets that don't match the above.
#

$IPTABLES -A OUTPUT -m limit --limit 3/minute --limit-burst 3 -j LOG \
--log-level DEBUG --log-prefix "IPT OUTPUT packet died: "

######
# 4.2 nat table
#

#
# 4.2.1 Set policies
#

#
# 4.2.2 Create user specified chains
#

#
# 4.2.3 Create content in user specified chains
#

#
# 4.2.4 PREROUTING chain
#

#
# 4.2.5 POSTROUTING chain
#

#
# Enable simple IP Forwarding and Network Address Translation
#

$IPTABLES -t nat -A POSTROUTING -o $INET_IFACE -j SNAT --to-source $INET_IP

#
# 4.2.6 OUTPUT chain
#

######
# 4.3 mangle table
#

#
# 4.3.1 Set policies
#

#
# 4.3.2 Create user specified chains
#

#
# 4.3.3 Create content in user specified chains
#

#
# 4.3.4 PREROUTING chain
#

#
# 4.3.5 INPUT chain
#

#
# 4.3.6 FORWARD chain
#

#
# 4.3.7 OUTPUT chain
#

#
# 4.3.8 POSTROUTING chain
#

   


I.4. ������
rc.DHCP.firewall

#!/bin/sh
#
# rc.firewall - DHCP IP Firewall script for Linux 2.4.x and iptables
#
# Copyright (C) 2001  Oskar Andreasson <bluefluxATkoffeinDOTnet>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program or from the site that you downloaded it
# from; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307   USA
#

###########################################################################
#
# 1. Configuration options.
#

#
# 1.1 Internet Configuration.
#

INET_IFACE="eth0"

#
# 1.1.1 DHCP
#

#
# Information pertaining to DHCP over the Internet, if needed.
#
# Set DHCP variable to no if you don't get IP from DHCP. If you get DHCP
# over the Internet set this variable to yes, and set up the proper IP
# address for the DHCP server in the DHCP_SERVER variable.
#

DHCP="no"
DHCP_SERVER="195.22.90.65"

#
# 1.1.2 PPPoE
#

# Configuration options pertaining to PPPoE.
#
# If you have problem with your PPPoE connection, such as large mails not
# getting through while small mail get through properly etc, you may set
# this option to "yes" which may fix the problem. This option will set a
# rule in the PREROUTING chain of the mangle table which will clamp
# (resize) all routed packets to PMTU (Path Maximum Transmit Unit).
#
# Note that it is better to set this up in the PPPoE package itself, since
# the PPPoE configuration option will give less overhead.
#

PPPOE_PMTU="no"

#
# 1.2 Local Area Network configuration.
#
# your LAN's IP range and localhost IP. /24 means to only use the first 24
# bits of the 32 bit IP address. the same as netmask 255.255.255.0
#

LAN_IP="192.168.0.2"
LAN_IP_RANGE="192.168.0.0/16"
LAN_IFACE="eth1"

#
# 1.3 DMZ Configuration.
#

#
# 1.4 Localhost Configuration.
#

LO_IFACE="lo"
LO_IP="127.0.0.1"

#
# 1.5 IPTables Configuration.
#

IPTABLES="/usr/sbin/iptables"

#
# 1.6 Other Configuration.
#

###########################################################################
#
# 2. Module loading.
#

#
# Needed to initially load modules
#

/sbin/depmod -a

#
# 2.1 Required modules
#

/sbin/modprobe ip_conntrack
/sbin/modprobe ip_tables
/sbin/modprobe iptable_filter
/sbin/modprobe iptable_mangle
/sbin/modprobe iptable_nat
/sbin/modprobe ipt_LOG
/sbin/modprobe ipt_limit
/sbin/modprobe ipt_MASQUERADE

#
# 2.2 Non-Required modules
#

#/sbin/modprobe ipt_owner
#/sbin/modprobe ipt_REJECT
#/sbin/modprobe ip_conntrack_ftp
#/sbin/modprobe ip_conntrack_irc
#/sbin/modprobe ip_nat_ftp
#/sbin/modprobe ip_nat_irc

###########################################################################
#
# 3. /proc set up.
#

#
# 3.1 Required proc configuration
#

echo "1" > /proc/sys/net/ipv4/ip_forward

#
# 3.2 Non-Required proc configuration
#

#echo "1" > /proc/sys/net/ipv4/conf/all/rp_filter
#echo "1" > /proc/sys/net/ipv4/conf/all/proxy_arp
#echo "1" > /proc/sys/net/ipv4/ip_dynaddr

###########################################################################
#
# 4. rules set up.
#

######
# 4.1 Filter table
#

#
# 4.1.1 Set policies
#

$IPTABLES -P INPUT DROP
$IPTABLES -P OUTPUT DROP
$IPTABLES -P FORWARD DROP

#
# 4.1.2 Create userspecified chains
#

#
# Create chain for bad tcp packets
#

$IPTABLES -N bad_tcp_packets

#
# Create separate chains for ICMP, TCP and UDP to traverse
#

$IPTABLES -N allowed
$IPTABLES -N tcp_packets
$IPTABLES -N udp_packets
$IPTABLES -N icmp_packets

#
# 4.1.3 Create content in userspecified chains
#

#
# bad_tcp_packets chain
#

$IPTABLES -A bad_tcp_packets -p tcp --tcp-flags SYN,ACK SYN,ACK \
-m state --state NEW -j REJECT --reject-with tcp-reset
$IPTABLES -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j LOG \
--log-prefix "New not syn:"
$IPTABLES -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j DROP

#
# allowed chain
#

$IPTABLES -A allowed -p TCP --syn -j ACCEPT
$IPTABLES -A allowed -p TCP -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPTABLES -A allowed -p TCP -j DROP

#
# TCP rules
#

$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 21 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 22 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 80 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 113 -j allowed

#
# UDP ports
#

$IPTABLES -A udp_packets -p UDP -s 0/0 --source-port 53 -j ACCEPT
if [ $DHCP == "yes" ] ; then
 $IPTABLES -A udp_packets -p UDP -s $DHCP_SERVER --sport 67 \
 --dport 68 -j ACCEPT
fi

#$IPTABLES -A udp_packets -p UDP -s 0/0 --source-port 53 -j ACCEPT
#$IPTABLES -A udp_packets -p UDP -s 0/0 --source-port 123 -j ACCEPT
$IPTABLES -A udp_packets -p UDP -s 0/0 --source-port 2074 -j ACCEPT
$IPTABLES -A udp_packets -p UDP -s 0/0 --source-port 4000 -j ACCEPT

#
# In Microsoft Networks you will be swamped by broadcasts. These lines
# will prevent them from showing up in the logs.
#

#$IPTABLES -A udp_packets -p UDP -i $INET_IFACE \
#--destination-port 135:139 -j DROP

#
# If we get DHCP requests from the Outside of our network, our logs will
# be swamped as well. This rule will block them from getting logged.
#

#$IPTABLES -A udp_packets -p UDP -i $INET_IFACE -d 255.255.255.255 \
#--destination-port 67:68 -j DROP

#
# ICMP rules
#

$IPTABLES -A icmp_packets -p ICMP -s 0/0 --icmp-type 8 -j ACCEPT
$IPTABLES -A icmp_packets -p ICMP -s 0/0 --icmp-type 11 -j ACCEPT

#
# 4.1.4 INPUT chain
#

#
# Bad TCP packets we don't want.
#

$IPTABLES -A INPUT -p tcp -j bad_tcp_packets

#
# Rules for special networks not part of the Internet
#

$IPTABLES -A INPUT -p ALL -i $LAN_IFACE -s $LAN_IP_RANGE -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $LO_IFACE -j ACCEPT

#
# Special rule for DHCP requests from LAN, which are not caught properly 
# otherwise.
#

$IPTABLES -A INPUT -p UDP -i $LAN_IFACE --dport 67 --sport 68 -j ACCEPT

#
# Rules for incoming packets from the internet.
#

$IPTABLES -A INPUT -p ALL -i $INET_IFACE -m state --state ESTABLISHED,RELATED \
-j ACCEPT
$IPTABLES -A INPUT -p TCP -i $INET_IFACE -j tcp_packets
$IPTABLES -A INPUT -p UDP -i $INET_IFACE -j udp_packets
$IPTABLES -A INPUT -p ICMP -i $INET_IFACE -j icmp_packets

#
# If you have a Microsoft Network on the outside of your firewall, you may
# also get flooded by Multicasts. We drop them so we do not get flooded by
# logs
#

#$IPTABLES -A INPUT -i $INET_IFACE -d 224.0.0.0/8 -j DROP

#
# Log weird packets that don't match the above.
#

$IPTABLES -A INPUT -m limit --limit 3/minute --limit-burst 3 -j LOG \
--log-level DEBUG --log-prefix "IPT INPUT packet died: "

#
# 4.1.5 FORWARD chain
#

#
# Bad TCP packets we don't want
#

$IPTABLES -A FORWARD -p tcp -j bad_tcp_packets

#
# Accept the packets we actually want to forward
#

$IPTABLES -A FORWARD -i $LAN_IFACE -j ACCEPT
$IPTABLES -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

#
# Log weird packets that don't match the above.
#

$IPTABLES -A FORWARD -m limit --limit 3/minute --limit-burst 3 -j LOG \
--log-level DEBUG --log-prefix "IPT FORWARD packet died: "

#
# 4.1.6 OUTPUT chain
#

#
# Bad TCP packets we don't want.
#

$IPTABLES -A OUTPUT -p tcp -j bad_tcp_packets

#
# Special OUTPUT rules to decide which IP's to allow.
#

$IPTABLES -A OUTPUT -p ALL -s $LO_IP -j ACCEPT
$IPTABLES -A OUTPUT -p ALL -s $LAN_IP -j ACCEPT
$IPTABLES -A OUTPUT -p ALL -o $INET_IFACE -j ACCEPT

#
# Log weird packets that don't match the above.
#

$IPTABLES -A OUTPUT -m limit --limit 3/minute --limit-burst 3 -j LOG \
--log-level DEBUG --log-prefix "IPT OUTPUT packet died: "

######
# 4.2 nat table
#

#
# 4.2.1 Set policies
#

#
# 4.2.2 Create user specified chains
#

#
# 4.2.3 Create content in user specified chains
#

#
# 4.2.4 PREROUTING chain
#

#
# 4.2.5 POSTROUTING chain
#

if [ $PPPOE_PMTU == "yes" ] ; then
 $IPTABLES -t nat -A POSTROUTING -p tcp --tcp-flags SYN,RST SYN \
 -j TCPMSS --clamp-mss-to-pmtu
fi
$IPTABLES -t nat -A POSTROUTING -o $INET_IFACE -j MASQUERADE

#
# 4.2.6 OUTPUT chain
#

######
# 4.3 mangle table
#

#
# 4.3.1 Set policies
#

#
# 4.3.2 Create user specified chains
#

#
# 4.3.3 Create content in user specified chains
#

#
# 4.3.4 PREROUTING chain
#

#
# 4.3.5 INPUT chain
#

#
# 4.3.6 FORWARD chain
#

#
# 4.3.7 OUTPUT chain
#

#
# 4.3.8 POSTROUTING chain
#

   


I.5. ������
rc.flush-iptables

#!/bin/sh
# 
# rc.flush-iptables - Resets iptables to default values. 
# 
# Copyright (C) 2001  Oskar Andreasson <bluefluxATkoffeinDOTnet>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program or from the site that you downloaded it
# from; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307   USA

#
# Configurations
#
IPTABLES="/usr/sbin/iptables"

#
# reset the default policies in the filter table.
#
$IPTABLES -P INPUT ACCEPT
$IPTABLES -P FORWARD ACCEPT
$IPTABLES -P OUTPUT ACCEPT

#
# reset the default policies in the nat table.
#
$IPTABLES -t nat -P PREROUTING ACCEPT
$IPTABLES -t nat -P POSTROUTING ACCEPT
$IPTABLES -t nat -P OUTPUT ACCEPT

#
# reset the default policies in the mangle table.
#
$IPTABLES -t mangle -P PREROUTING ACCEPT
$IPTABLES -t mangle -P OUTPUT ACCEPT

#
# flush all the rules in the filter and nat tables.
#
$IPTABLES -F
$IPTABLES -t nat -F
$IPTABLES -t mangle -F
#
# erase all chains that's not default in filter and nat table.
#
$IPTABLES -X
$IPTABLES -t nat -X
$IPTABLES -t mangle -X



   


I.6. ������
rc.test-iptables

#!/bin/bash
#
# rc.test-iptables - test script for iptables chains and tables.
#
# Copyright (C) 2001  Oskar Andreasson <bluefluxATkoffeinDOTnet>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program or from the site that you downloaded it
# from; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307   USA
#

#
# Filter table, all chains
#
iptables -t filter -A INPUT -p icmp --icmp-type echo-request \
-j LOG --log-prefix="filter INPUT:"
iptables -t filter -A INPUT -p icmp --icmp-type echo-reply \
-j LOG --log-prefix="filter INPUT:"
iptables -t filter -A OUTPUT -p icmp --icmp-type echo-request \
-j LOG --log-prefix="filter OUTPUT:"
iptables -t filter -A OUTPUT -p icmp --icmp-type echo-reply \
-j LOG --log-prefix="filter OUTPUT:"
iptables -t filter -A FORWARD -p icmp --icmp-type echo-request \
-j LOG --log-prefix="filter FORWARD:"
iptables -t filter -A FORWARD -p icmp --icmp-type echo-reply \
-j LOG --log-prefix="filter FORWARD:"

#
# NAT table, all chains except OUTPUT which don't work.
#
iptables -t nat -A PREROUTING -p icmp --icmp-type echo-request \
-j LOG --log-prefix="nat PREROUTING:"
iptables -t nat -A PREROUTING -p icmp --icmp-type echo-reply \
-j LOG --log-prefix="nat PREROUTING:"
iptables -t nat -A POSTROUTING -p icmp --icmp-type echo-request \
-j LOG --log-prefix="nat POSTROUTING:"
iptables -t nat -A POSTROUTING -p icmp --icmp-type echo-reply \
-j LOG --log-prefix="nat POSTROUTING:"
iptables -t nat -A OUTPUT -p icmp --icmp-type echo-request \
-j LOG --log-prefix="nat OUTPUT:"
iptables -t nat -A OUTPUT -p icmp --icmp-type echo-reply \
-j LOG --log-prefix="nat OUTPUT:"

#
# Mangle table, all chains
#
iptables -t mangle -A PREROUTING -p icmp --icmp-type echo-request \
-j LOG --log-prefix="mangle PREROUTING:"
iptables -t mangle -A PREROUTING -p icmp --icmp-type echo-reply \
-j LOG --log-prefix="mangle PREROUTING:"
iptables -t mangle -I FORWARD 1 -p icmp --icmp-type echo-request \
-j LOG --log-prefix="mangle FORWARD:"
iptables -t mangle -I FORWARD 1 -p icmp --icmp-type echo-reply \
-j LOG --log-prefix="mangle FORWARD:"
iptables -t mangle -I INPUT 1 -p icmp --icmp-type echo-request \
-j LOG --log-prefix="mangle INPUT:"
iptables -t mangle -I INPUT 1 -p icmp --icmp-type echo-reply \
-j LOG --log-prefix="mangle INPUT:"
iptables -t mangle -A OUTPUT -p icmp --icmp-type echo-request \
-j LOG --log-prefix="mangle OUTPUT:"
iptables -t mangle -A OUTPUT -p icmp --icmp-type echo-reply \
-j LOG --log-prefix="mangle OUTPUT:"
iptables -t mangle -I POSTROUTING 1 -p icmp --icmp-type echo-request \
-j LOG --log-prefix="mangle POSTROUTING:"
iptables -t mangle -I POSTROUTING 1 -p icmp --icmp-type echo-reply \
-j LOG --log-prefix="mangle POSTROUTING:"

   

Состояние перевода: На этой странице представлен перевод статьи iptables. Дата последней синхронизации: 10 июля 2021. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.

iptables — утилита командной строки для настройки встроенного в ядро Linux межсетевого экрана, разработанного в рамках проекта Netfilter. Термином iptables также часто называют сам межсетевой экран в ядре. Настройка экрана выполняется либо напрямую с помощью iptables, либо через один из фронтендов, консольных или графических. iptables работает с протоколом IPv4, для IPv6 разработана утилита ip6tables. В основном их синтаксис совпадает, но некоторые специфичные для протоколов опции различаются.

Примечание: Фреймворк iptables постепенно выходит из употребления; более современная замена — nftables, в котором предусмотрен слой совместимости.

Установка

Стандартное ядро Arch Linux скомпилировано с поддержкой iptables. Необходимо лишь установить набор пользовательских утилит, которые собраны в пакет iptables. Поскольку данный пакет является косвенной зависимостью мета-пакета base, то он по умолчанию должен быть установлен в системе.

Фронтенды

Консольные

  • Arno’s firewall — безопасный межсетевой экран как для одиночной машины, так и для разрозненной сети. Лёгок в настройке, удобен в использовании, хорошо кастомизируется. Поддерживает: NAT и SNAT, проброс портов, ADSL ethernet-модемы со статическими и динамическими IP-адресами, фильтрацию MAC-адресов, обнаружение скрытого сканирования портов, DMZ и DMZ-2-LAN пересылку, защиту от SYN/ICMP флуда, обширное логирование с временными ограничениями для предотвращения засорения логов, все IP-протоколы и технологии VPN вроде IPsec, плагины для расширения функциональности.
https://rocky.eld.leidenuniv.nl/ || arno-iptables-firewallAUR
  • ferm — инструмент для обслуживания комплексных межсетевых экранов, помогающий избежать необходимости переписывать сложные правила снова и снова. Позволяет сохранить целый набор правил в одном файле и загрузить его всего одной командой. Настройка экрана производится посредством специального языка, наподобие языка программирования, с помощью уровней и списков.
http://ferm.foo-projects.org/ || ferm
  • FireHOL — не только программа для создания межсетевого экрана, но и специальный язык для задания его настроек. Делает даже тонкую настройку экрана лёгкой — как вам бы и хотелось.
http://firehol.sourceforge.net/ || fireholAUR
  • Firetable — инструмент для межсетевого экрана iptables. Каждый сетевой интерфейс настраивается отдельно в соответствии с собственным файлом настроек, синтаксис которого понятен и удобен.
https://gitlab.com/hsleisink/firetable || firetableAUR
  • firewalld (firewall-cmd) — демон и консольный интерфейс для настройки сети, зональной политики и правил межсетевого экрана.
https://firewalld.org/ || firewalld
  • Shorewall — высокоуровневый инструмент для настройки Netfilter. Требования к экрану/шлюзу описываются посредством записей в наборе файлов настроек.
http://www.shorewall.net/ || shorewallAUR
  • Uncomplicated Firewall — простой интерфейс для iptables.
https://launchpad.net/ufw || ufw
  • PeerGuardian (pglcmd) — ориентированное на приватность firewall-приложение. Занимается блокировкой входящих и исходящих подключений на основе огромного чёрного списка (тысячи или даже миллионы IP-диапазонов).
https://sourceforge.net/projects/peerguardian/ || pglAUR
  • Vuurmuur — мощный менеджер сетевого экрана. Лёгкая в освоении настройка, которая позволяет создавать как простые, так и сложные конфигурации межсетевого экрана. Для настройки есть графический интерфейс на основе ncurses, который позволяет осуществлять безопасное удалённое администрирование через SSH или консоль. Vuurmuur поддерживает ограничение трафика, имеет мощную систему мониторинга, которая позволяет администратору следить за логами, подключениями и использованием пропускной способности в режиме реального времени.
https://www.vuurmuur.org/ || vuurmuurAUR

Графические

  • Firewall Builder — графический интерфейс для настройки и управления межсетевыми экранами, работает с iptables (netfilter), ipfilter, pf, ipfw, Cisco PIX (FWSM, ASA), а также с маршрутизаторами Cisco с поддержкой Extended ACL. Запускается на Linux, FreeBSD, OpenBSD, Windows и macOS, может управлять как локальными, так и удалёнными межсетевыми экранами.
https://fwbuilder.sourceforge.net/ || fwbuilder
  • firewalld (firewall-config) — демон и графический интерфейс для настройки сети, зональной политики и правил межсетевого экрана.
https://firewalld.org/ || firewalld
  • Gufw — графический GTK-интерфейс для ufw, который, в свою очередь, является интерфейсом командной строки для iptables (gufw–>ufw–>iptables), лёгкий и простой в использовании.
https://gufw.org/ || gufw
  • PeerGuardian GUI (pglgui) — ориентированное на приватность firewall-приложение. Занимается блокировкой входящих и исходящих подключений на основе огромного чёрного списка (тысячи или даже миллионы IP-диапазонов).
https://sourceforge.net/projects/peerguardian/ || pglAUR

Основные понятия

iptables используется для проверки, модификации, перенаправления и отбрасывания пакетов. Код для фильтрации пакетов IPv4 уже встроен в ядро и организован в виде набора таблиц, каждая из которых предназначена для конкретной цели. Таблица состоит из группы предопределённых цепочек, а те, в свою очередь, содержат правила, которые проверяются по очереди. Каждое правило состоит из критерия (набора условий) и действия (т.н. цели); действие применяется к пакету, подпадающему под критерий (т. е. если все условия выполнены). Если пакет достигает конца встроенной цепочки, в том числе пустой, то он отправляется дальше в соответствии с политикой цепочки. iptables — пользовательская утилита для работы с цепочками и правилами. Большинство пользователей находят IP-маршрутизацию Linux сложной и запутанной, однако на практике наиболее распространенные варианты использования (NAT и/или базовый межсетевой экран для интернета) являются значительно менее сложными.

Ключ к пониманию принципа работы iptables находится в этой блок-схеме. Слова в нижнем регистре в верхней части каждого блока являются именами таблиц, а слова в верхнем регистре – цепочками. Каждый IP-пакет, принятый на любом сетевом интерфейсе, проходит через эту блок-схему сверху вниз. Существует заблуждение, что пакеты, приходящие на внутренний интерфейс, обрабатываются как-то иначе нежели те, что приходят на интерфейс, подключённый к интернету. Пакеты на всех интерфейсах обрабатываются одинаково; это ваша задача написать правила, которые будут обрабатывать их по-разному. Некоторые пакеты предназначены для локальных процессов; они проходят по схеме от верхнего блока до блока <Local Process> (локальный процесс). В то же время локальный процесс сам может генерировать пакеты, и они начинают путешествие по схеме с блока <Local Process> и далее вниз. Подробное описание работы этой блок-схемы можно найти здесь.

В подавляющем большинстве случаев таблицы raw, mangle и security вам не понадобятся. На схеме ниже приведён упрощённый вариант прохождения пакета через iptables:

                               XXXXXXXXXXXXXXXXXX
                             XXX      Сеть      XXX
                               XXXXXXXXXXXXXXXXXX
                                       +
                                       |
                                       v
+---------------+             +-------------------+
|таблица: filter| <---+       |таблица: nat       |
|цепочка: INPUT |     |       |цепочка: PREROUTING|
+-------+-------+     |       +--------+----------+
        |             |                |
        v             |                v
[локальный процесс]   |         ***************          +----------------+
        |             +-------+  Маршрутизация  +------> |таблица: filter |
        v                       ***************          |цепочка: FORWARD|
 ***************                                         +-------+--------+
  Маршрутизация                                                  |
 ***************                                                 |
        |                                                        |
        v                       ***************                  |
+---------------+     +------>   Маршрутизация   <---------------+
|таблица: nat   |     |         ***************
|цепочка: OUTPUT|     |                +
+------+--------+     |                |
        |             |                v
        v             |      +---------------------+
+---------------+     |      | таблица: nat        |
|таблица: filter| +---+      | цепочка: POSTROUTING|
|цепочка: OUTPUT|            +---------+-----------+
+---------------+                      |
                                       v
                               XXXXXXXXXXXXXXXXXX
                             XXX      Сеть      XXX
                               XXXXXXXXXXXXXXXXXX

Таблицы

iptables содержит пять таблиц:

  1. raw — используется только для настройки пакетов, поэтому они освобождаются от отслеживания.
  2. filter — таблица по умолчанию; в ней сосредоточены все действия, типичные для межсетевых экранов.
  3. nat — используется для преобразования сетевых адресов (например, проброс портов).
  4. mangle — используется для специальных преобразований пакетов.
  5. security — используется в сетевых правилах для Мандатного управления доступом (например, в SELinux – подробнее см. эту статью).

Скорее всего, вам потребуются только две из них: filter и nat. Остальные таблицы используются в сложных конфигурациях с несколькими маршрутизаторами и выходят за рамки данной статьи.

Цепочки

Таблицы состоят из цепочек, которые представляют собой набор правил, следующих друг за другом в определённом порядке. Таблица по умолчанию, filter, содержит три встроенные цепочки: INPUT, OUTPUT и FORWARD, которые, как видно из диаграммы, активируются в определённые моменты процесса фильтрации пакетов. Таблица nat включает стандартные цепочки PREROUTING, POSTROUTING и OUTPUT.

Описание стандартных цепочек других таблиц можно найти в руководстве iptables(8).

По умолчанию все цепочки пусты и не содержат каких-либо правил. Вы должны добавить правила в те цепочки, которые собираетесь использовать. У цепочек также задана политика по умолчанию — обычно ACCEPT, но её можно изменить на DROP, если вы хотите убедиться, что ни один пакет не проскочит мимо вашего набора правил. Тем не менее, политика по умолчанию применяется к пакету только после того, как он пройдёт через все существующие правила.

Вы можете добавить собственные цепочки для большей эффективности или удобства. Пример создания таких цепочек можно найти в статье Настройка межсетевого экрана.

Правила

Фильтрация пакетов основана на правилах. Каждое правило состоит из нескольких условий и действия-цели. Если пакет соответствует всем условиям, то к нему применяется указанное действие. Распространённые условия для проверки — на какой интерфейс пришёл пакет (например, eth0 или eth1), какого он типа (ICMP, TCP или UDP) или на какой порт направляется.

Цели указываются опцией -j/--jump. Цель может быть встроеной (built-in), целью-расширением (extension) или переходом на пользовательскую цепочку. Встроенные цели — ACCEPT, DROP, QUEUE и RETURN; цели-расширения, к примеру — REJECT и LOG. Если применяется встроенная цель, то участь пакета решается незамедлительно и обработка пакета в таблице прекращается. Если в качестве цели выбран переход на пользовательскую цепочку, то пакет проходит через неё, возвращается в исходную цепочку и продолжает со следующего после перехода правила. Цели-расширения могут быть завершающими (как встроенные) или незавершающими (как пользовательские цепочки). Подробнее см. iptables-extensions(8).

Прохождение по цепочке

Принятый на сетевом интерфейсе пакет проходит по цепочкам таблиц в порядке, изображённом на диаграмме. В первой точке маршрутизации (routing decision) принимается решение, направляется ли пакет на локальную машину (в таком случае пакет проходит через цепочку INPUT) или куда-то в другое место (в этом случае пакет проходит через цепочку FORWARD). Последующие точки маршрутизации определяют, на какой сетевой интерфейс направить исходящий пакет. В каждой цепочке по пути следования пакета последовательно проверяются все правила, и если пакет удовлетворяет условиям правила, то выполняется соответствующее действие-цель. Три наиболее частых цели – ACCEPT, DROP и переход на пользовательскую цепочку. В противоположность встроенным цепочкам, которые имеют цели по умолчанию, цепочки пользователя такой цели не имеют. Если не удовлетворены условия ни одного из правил пользовательской цепочки, пакет возвращается обратно в вызвавшую её цепочку, как показано здесь. Если в какое-то момент выполнились все условия цепочки с действием DROP, пакет немедленно отбрасывается и над ним более не производится никаких действий. Обратите, однако, внимание, что если пакет принят действием ACCEPT, он принимается только в текущей цепочке и в вышележащих цепочках в текущем стеке вызовов. Он не обрабатывается более той стандартной цепочкой, которая инициировала последовательность переходов, но продолжает проходить по цепочкам в других таблицах обычным образом.

Модули

Существует ряд модулей для расширения возможностей iptables, среди которых connlimit, conntrack, limit и recent. Эти модули добавляют новую функциональность в iptables, что позволяет создавать более сложные правила фильтрации.

Настройка и использование

iptables — служба systemd и запускается соответственно. Пакет iptables при установке добавляет пустой комплект правил /etc/iptables/iptables.rules, который будет загружен при первом запуске службы iptables.service. Как и прочие службы, службу iptables для добавления в автозапуск необходимо включить.

Правила iptables для IPv6 по умолчанию хранятся в файле /etc/iptables/ip6tables.rules, который используется службой ip6tables.service. Эту службу можно запустить так же, как и iptables.service.

После добавления правил посредством командной строки файл настроек не изменится автоматически — изменения необходимо сохранять командой:

# iptables-save -f /etc/iptables/iptables.rules

Если вы изменяли файл настроек вручную, то либо перезагрузите службу iptables, либо загрузите настройки вручную командой:

# iptables-restore /etc/iptables/iptables.rules

Из командной строки

Вывод текущих правил

Основная команда для вывода текущих правил — --list-rules/-S; её вывод похож на вывод утилиты iptables-save. Разница между ними в том, что по умолчанию последняя выводит правила из всех таблиц, в то время как iptables — только из таблицы filter.

Команда --list/-L принимает больше модификаторов и выводит более подробную информацию. Например, следующая команда позволяет проверить текущий набор правил и количество срабатываний каждого из них:

# iptables -nvL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Представленный выше вывод свидетельствует о том, что в таблице по умолчанию (filter) никакие правила не заданы и все пакеты пропускаются. Выбрать другую таблицу можно опцией -t.

Чтобы вывести номера строк при просмотре правил, запустите команду с опцией --line-numbers. Это бывает удобно для последующего редактирования правил в командной строке.

Сброс правил

Сбросить правила iptables можно следующими командами:

# iptables -F
# iptables -X
# iptables -t nat -F
# iptables -t nat -X
# iptables -t mangle -F
# iptables -t mangle -X
# iptables -t raw -F
# iptables -t raw -X
# iptables -t security -F
# iptables -t security -X
# iptables -P INPUT ACCEPT
# iptables -P FORWARD ACCEPT
# iptables -P OUTPUT ACCEPT

Команда -F без аргументов просто очищает все цепочки в текущей таблице. Аналогично, команда -X удаляет все пустые пользовательские цепочки в таблице.

Отдельные цепочки могут быть очищены от правил или удалены указанием имени цепочки после команд -F и -X соответственно.

Редактирование правил

Редактирование правил подразумевает одно из следующих действий: добавление правила в конец цепочки (-A), вставка правила в конкретную позицию в цепочке (-I), замена (-R) и удаление (-D) существующего правила.

Примеры ниже приведены исходя из соображения, что компьютер не является маршрутизатором. Поэтому первым делом меняем политику цепочки FORWARD с ACCEPT на DROP:

# iptables -P FORWARD DROP

Важно: Этот раздел не претендует на роль руководства по защите серверов. Его назначение — научить синтаксису и принципам правил iptables. Изучите статью Настройка межсетевого экрана, в которой приведена минимально безопасная конфигурация iptables, а также страницу Безопасность, где рассмотрена защита системы в целом.

Синхронизация по локальной сети в Dropbox производится с помощью отправки широковещательных пакетов каждые 30 секунд всем доступным компьютерам сети. Если вы находитесь в локальной сети с клиентами Dropbox и не желаете использовать эту возможность, то следует отклонять такие пакеты:

# iptables -A INPUT -p tcp --dport 17500 -j REJECT --reject-with icmp-port-unreachable
# iptables -nvL --line-numbers
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination
1        0     0 REJECT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:17500 reject-with icmp-port-unreachable

Chain FORWARD (policy DROP 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Примечание: Здесь используется действие REJECT, а не DROP, так как в RFC 1122 указано требование к хостам возвращать ICMP-ошибки всегда, когда это возможно, вместо простого отбрасывания пакета. На этой странице поясняется, почему REJECT почти всегда лучше DROP.

Теперь предположим, что вы поменяли своё мнение касательно Dropbox и решили установить его на компьютере. Также вы режили использовать синхронизацию, но с одним конкретным IP-адресом (например, 10.0.0.85). Команда -R позволяет заменить существующее правило:

# iptables -R INPUT 1 -p tcp --dport 17500 ! -s 10.0.0.85 -j REJECT --reject-with icmp-port-unreachable
# iptables -nvL --line-numbers
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination
1        0     0 REJECT     tcp  --  *      *      !10.0.0.85            0.0.0.0/0            tcp dpt:17500 reject-with icmp-port-unreachable

Chain FORWARD (policy DROP 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Новое правило позволяет хосту 10.0.0.85 отправить данные на порт 17500 вашего компьютера. Но вдруг вы понимаете, что этот подход не масштабируется. Если дружественный пользователь Dropbox пытается получить доступ к порту 17500, то мы хотим предоставлять ему доступ немедленно, не проверяя его последующими правилами!

Поэтому мы пишем новое правило для предоставления доверенному пользователю немедленного доступа и добавляем его командой -I, чтобы вставить его перед предыдущим:

# iptables -I INPUT -p tcp --dport 17500 -s 10.0.0.85 -j ACCEPT -m comment --comment "Friendly Dropbox"
# iptables -nvL --line-numbers
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination
1        0     0 ACCEPT     tcp  --  *      *       10.0.0.85            0.0.0.0/0            tcp dpt:17500 /* Friendly Dropbox */
2        0     0 REJECT     tcp  --  *      *      !10.0.0.85            0.0.0.0/0            tcp dpt:17500 reject-with icmp-port-unreachable

Chain FORWARD (policy DROP 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Второе правило теперь можно переписать так, чтобы оно отбрасывало все пакеты на порт 17500 с других хостов:

# iptables -R INPUT 2 -p tcp --dport 17500 -j REJECT --reject-with icmp-port-unreachable

Итоговый список правил теперь выглядит следующим образом:

# iptables -nvL --line-numbers
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination
1        0     0 ACCEPT     tcp  --  *      *       10.0.0.85            0.0.0.0/0            tcp dpt:17500 /* Friendly Dropbox */
2        0     0 REJECT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:17500 reject-with icmp-port-unreachable

Chain FORWARD (policy DROP 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Руководства

  • Настройка межсетевого экрана
  • Router

Журналирование

Цель LOG позволяет при срабатывании правила добавлять информацию о пакете в журнал. В отличие от прочих целей, вроде ACCEPT или DROP, при срабатывании цели LOG пакет продолжает продвижение по цепочке. Поэтому, например, чтобы включить журналирование всех отброшенных пакетов, необходимо перед каждым DROP-правилом добавить аналогичное LOG-правило. Правда, это не очень выгодно с точки зрения эффективности и удобства, и вместо этого лучше создать отдельную цепочку logdrop:

# iptables -N logdrop

Добавьте в неё следующие правила:

# iptables -A logdrop -m limit --limit 5/m --limit-burst 10 -j LOG
# iptables -A logdrop -j DROP

Опции limit и limit-burst объяснены следующем разделе.

Теперь для отбрасывания пакета с добавлением соответствующей записи в журнал необходимо просто выполнить переход на цепочку logdrop:

# iptables -A INPUT -m conntrack --ctstate INVALID -j logdrop

Ограничение скорости логирования

Цепочка logdrop из предыдущего раздела использует модуль limit, который помогает предотвратить разрастание журнала и избежать ненужных операций записи на диск. Если этого не сделать, то неправильно настроенная служба, которая пытается установить соединение, или просто злоумышленник, могут привести к исчерпанию свободного места на диске (как минимум в разделе /var) из-за добавления чрезмерного количества записей в журнал.

Модуль limit подключается опцией -m limit. Опцией --limit задаётся средняя скорость журналирования, а опцией --limit-burst — начальная. В примере цепочки logdrop выше команда

# iptables -A logdrop -m limit --limit 5/m --limit-burst 10 -j LOG

добавляет правило, которое логирует все проходящие через него пакеты. Первые 10 пакетов будут добавлены в журнал, но затем скорость логирования не будет превышать 5 пакетов в минуту. Если значение limit какое-то время не нарушается, то limit-burst снова «разблокируется», т.е. журналирование автоматически вернётся к нормальному режиму.

Просмотр логированных пакетов

В журнале systemd логированные пакеты отображаются как сообщения ядра.

Следующая команда выведет список пакетов, добавленных журнал с момента последней загрузки системы:

# journalctl -k --grep="IN=.*OUT=.*"

syslog-ng

Если вы используете syslog-ng, то в файле syslog-ng.conf можно настроить место хранения логов iptables. Замените:

filter f_everything { level(debug..emerg) and not facility(auth, authpriv); };

на

filter f_everything { level(debug..emerg) and not facility(auth, authpriv) and not filter(f_iptables); };

После этого вывод iptables больше не будет отправляться в /var/log/everything.log.

Если необходимо задать произвольный файл для хранения журнала iptables (вместо /var/log/iptables.log), то измените значение пути в параметре d_iptables (в том же файле (syslog-ng.conf):

destination d_iptables { file("/var/log/iptables.log"); };

ulogd

ulogd — работающий в пространстве пользователя специализированный демон журналирования пакетов для netfilter, который может заменить стандартную цель LOG.

Смотрите также

  • Iptables в Википедии
  • Port knocking
  • Официальный сайт iptables
  • Руководство по iptables версии 1.2.2 от Oskar Andreasson
  • Debian Wiki — iptables
  • Безопасное использование Connection Tracking helpers

Рассмотрим использование наиболее популярного в дистрибутивах Linux межсетевого экрана iptables на примере облачной платформы Selectel. Описанные в статье действия производились в Ubuntu 20.04 LTS 64-bit.

Подготовка сервера

Сначала необходимо пройти регистрацию, если еще нет аккаунта, затем войти в панель управления. В меню Облачная платформаСоздать проект, задать имя проекта, нажать кнопку Создать проект. Появится кнопка Создать сервер, нажимаем.

Будет показана страница Новый сервер, где необходимо указать имя сервера, регион (если необходимо). Чтобы выбрать образ нужной операционной системы, нажимаем кнопку Выбрать другой источник.

Во всплывающем меню, в колонке Операционные системы выбираем Ubuntu, слева появится список разных версий ОС, доступных к установке. Выбираем Ubuntu 20.04 LTS 64-bit и нажимаем кнопку Выбрать.

Двигаемся вниз по странице, ставим флаг Локальный диск. В области Сетевые диски нажимаем кнопку Удалить диск, для нашего примера этого достаточно.

В настройках Сеть выбираем Публичный IP-адрес, значение в поле должно измениться на Новый плавающий IP-адрес.

Добравшись до пункта меню Доступ, скопируйте Пароль для root, он необходим для взаимодействия с сервером через SSH-протокол. Важно: у способа подключения по паролю есть более безопасная альтернатива — подключение к серверу по SSH-ключу. Подробнее об этом читайте по ссылке.

После нажатия кнопки Создать ориентировочно через одну минуту сервер будет доступен. Заходим в меню Облачная платформаСерверы.

В списке отобразится информация о ранее созданном сервере. Статус сервера ALIVE означает, что сервер активен и готов к работе. Область, помеченная цифрой 3, содержит IP-адрес, по которому будем подключаться, используя любой SSH-клиент, например PuTTY для Windows.

Выполним первоначальную настройку сервера с целью повышения степени защищенности системы. Все действия, описанные в данной статье, выполняются с правами суперпользователя root.

Актуализируем информацию о доступных пакетах в используемых репозиториях:

apt update

С точки зрения безопасности заходить на сервер сразу пользователем root неправильно, поэтому создаем непривилегированного пользователя с именем fwuser:

adduser fwuser

В ходе интерактивного диалога необходимо задать пароль (New password), подтвердить его (Retype new password). Другие пункты заполнять не обязательно, можно проигнорировать их, нажимая ENTER. В финальном вопросе Is the information correct? [Y/n] нажимаем Y, затем ENTER.

Добавляем пользователя fwuser в группу sudo для возможности использования повышенных прав в системе:

usermod -aG sudo fwuser

Редактируем конфигурационный файл SSH-сервера:

nano /etc/ssh/sshd_config

Рекомендуется сменить стандартный номер порта, допустим на 22200. Находим строку #Port 22 и приводим ее к виду:

Port 22200

Запретим входить напрямую пользователем root. Ищем строку PermitRootLogin yes, меняем значение на no, в итоге строка выглядит так:

PermitRootLogin no

Нажимаем комбинацию клавиш Ctrl+O, внизу отобразится строка: File Name to Write: /etc/ssh/sshd_config, подтверждаем нажатием ENTER. Изменения сохранены, теперь выходим из редактора нажатием сочетания клавиш Ctrl+X.

Для вступления в силу изменений конфигурации SSH-сервера перезапускаем его:

service sshd restart

Важно заметить, что при следующем подключении к серверу, подключаться нужно к порту 22200. Вход пользователю root запрещен. Авторизоваться необходимо вновь созданным пользователем fwuser, и только после успешного входа, следует повысить уровень привилегий в системе командой:

sudo su

Система попросит ввести свой пароль (не root) и нажать ENTER, если следующая строка начинается на root, а заканчивается знаком # — привилегии суперпользователя получены успешно.

Что такое iptables

iptables — это утилита командной строки, используемая для управления встроенным брандмауэром netfilter, доступным в ядре Linux, начиная с версии 2.4. Брандмауэр — это приложение, на котором происходит фильтрация сетевого трафика на основе заданных администратором правил. Обеспечить безопасность сервера или инфраструктуры, означает обеспечить отказоустойчивость и стабильность работы ваших серверов и приложений, что крайне чувствительно для бизнеса или персональных проектов.

В глобальной сети огромное количество угроз — боты, периодически прощупывают стандартные точки входа в системы, хулиганы, любопытные, взломщики — люди, целенаправленно пытающиеся получить несанкционированный доступ к информационным системам. Задача iptables — исключить либо хотя бы минимизировать негативное воздействие со стороны разного рода правонарушителей.

Установка iptables

Список образов операционных систем, доступных к установке в облачной платформе Selectel, где iptables уже включен в дистрибутив:

  • CentOS 7 Minimal 64-bit;
  • CentOS 7 64-bit;
  • Debian 9 (Stretch) 64-bit;
  • Debian 10 (Buster) 64-bit;
  • Ubuntu 16.04 LTS 64-bit;
  • Ubuntu 18.04 LTS 64-bit;
  • Ubuntu 18.04 LTS Machine Learning 64-bit;
  • Ubuntu 20.04 LTS 64-bit.

Убедиться в этом можно при помощи команды:

iptables -V

Будет выведена информация о версии пакета.

В образах CentOS 8 64-bit и CentOS 8 Stream 64-bit iptables отсутствует, поскольку разработчики отказались от него в пользу более нового пакета — nftables. Его поддержка на уровне ядра доступна с версии 3.13. Если существует необходимость использовать именно iptables, требуется выполнить следующий порядок действий:

yum install iptables-services

Включение сервиса в автозагрузку:

systemctl enable iptables

Запуск сервиса:

systemctl start iptables

Межсетевой экран готов к использованию.

Порядок прохождения таблиц и цепочек

Любой поступивший пакет на сервер с iptables проходит через ядро, а именно — межсетевой экран netfilter. Каждый из них классифицируется в зависимости от его назначения, попадает в соответствующую ему таблицу и проходит по цепочкам, содержащим правила, установленные администратором.

На основе этих правил выполняется действие: принять пакет, отбросить, удалить или передать следующему узлу сети. Иллюстрация, представленная ниже, наглядно показывает путь прохождения пакета по системе:

Данный рисунок не отражает истинную архитектуру брандмауэра, а показывает только логику работы. Существует много распространенных заблуждений по поводу уровней вложенности таблиц, цепочек, и правил. Самым верхним уровнем представления являются таблицы, которые содержат набор свойственных им цепочек. Цепочки содержат списки правил. Схематично «матрешка» выглядит следующим образом:

Синтаксис iptables

Сетевой экран iptables очень гибок в настройке и имеет огромное количество разнообразных ключей и опций. Общий вид управляющей команды:

iptables таблица команда цепочка критерии действие

Рассмотрим каждый элемент в отдельности.

Пакет

Под пакетом понимают структурированный блок данных, содержащий в себе как пользовательскую информацию, называемую ещё полезной нагрузкой, так и служебную информацию, например об адресе отправителя, получателя, времени жизни пакета и многое другое.

Цепочки

Существует 5 видов цепочек:

  • PREROUTING — предназначена для первичной обработки входящих пакетов, адресованных как непосредственно серверу, так и другим узлам сети. Сюда попадает абсолютно весь входящий трафик для дальнейшего анализа.
  • INPUT — для входящих пакетов, отправленных непосредственно этому серверу.
  • FORWARD — для проходящих пакетов, не адресованных этому компьютеру, предназначены для передачи следующему узлу, в случае, если сервер выполняет роль маршрутизатора.
  • OUTPUT — для пакетов, отправленных с этого сервера.
  • POSTROUTING — здесь оказываются пакеты, предназначенные для передачи на другие узлы сети.

Также есть возможность создавать и удалять собственные цепочки, в большинстве случаев, в этом нет необходимости. Названия цепочек пишут заглавными буквами.

Таблицы

В netfilter существуют 5 типов таблиц, каждая из них имеет свое назначение.

Таблица raw

Содержит цепочки PREROUTING и OUTPUT, здесь производятся манипуляции с пакетами до задействования механизма определения состояний.

Таблица mangle

Предназначена для модификации заголовков сетевых пакетов, таких параметров как ToS (Type of Service), TTL (Time To Live), MARK. Содержит все существующие пять цепочек.

Таблица nat

Используется для трансляции сетевых адресов, т.е. подмены адреса получателя/отправителя, применяется, если сервер используется в качестве маршрутизатора. Содержит цепочки PREROUTING, OUTPUT, POSTROUTING.

Таблица filter

Основная таблица, служит для фильтрации пакетов, именно здесь происходит принятие решений о разрешении или запрете дальнейшего движения пакета в системе. Используется по умолчанию, если явно не указано имя другой таблицы. Содержит цепочки INPUT, FORWARD и OUTPUT.

Таблица security

Используется для взаимодействия с внешними системами безопасности, в частности с SELinux и AppArmor. Содержит цепочки INPUT, OUTPUT и FORWARD.

Имена таблиц принято писать строчными буквами.

Действия

Правилами задается поведение для iptables, каким образом поступить с тем или иным пакетом при попадании под заданные критерии. Решения, которые принимает брандмауэр, называют действиями, самые распространенные из них:

  • ACCEPT — разрешить дальнейшее прохождение пакета по системе;
  • DROP — выбросить пакет без уведомления отправителя;
  • REJECT — отказать в прохождении пакета с уведомлением отправителя, такой способ может привести к дополнительным затратам ресурсов процессора, поэтому, в большинстве случаев рекомендуется использовать DROP;
  • LOG — зафиксировать информацию о пакете в файле системного журнала;
  • MARK — позволяет помечать определенные пакеты, например для маршрутизации, данная метка перестает существовать, как только пакет покинет брандмауэр;
  • CONNMARK — то же самое, что и MARK, только для соединений;
  • QUEUE — отправляет пакет в очередь приложению для дальнейшего взаимодействия;
  • RETURN — прекращение движения пакета по текущей цепочке и возврат в предыдущую цепочку. Если текущая цепочка единственная — к пакету будет применено действие по умолчанию;
  • REDIRECT — перенаправляет пакет на указанный порт, в пределах этого же узла, применяется для реализации «прозрачного» прокси;
  • DNAT — подменяет адрес получателя в заголовке IP-пакета, основное применение — предоставление доступа к сервисам снаружи, находящимся внутри сети;
  • SNAT — служит для преобразования сетевых адресов, применимо, когда за сервером находятся машины, которым необходимо предоставить доступ в Интернет, при этом от провайдера имеется статический IP-адрес;
  • MASQUERADE — то же, что и SNAT, но главное отличие в том, что может использоваться, когда провайдер предоставляет динамический адрес, создаёт дополнительную нагрузку на систему по сравнению с SNAT;
  • TOS — позволяет управлять битами в одноименном поле заголовка IP-пакета;
  • ULOG — более продвинутый вариант записи информации, может писать как в обычный текстовый файл, так и в базу данных;
  • TTL — используется для изменения значения поля одноименного заголовка IP-пакета, устанавливает время жизни пакета.

Команды

Для iptables команда — это инструкция к действию, при помощи них можно добавлять, удалять и сбрасывать все правила, задавать действия по умолчанию и многое другое. Команды могут подаваться как в сокращенном, так и в полном виде, более подробно в таблице:

Полный вид Сокращенный вид Описание
—append -A добавить правило в конец указанной цепочки
—check -C проверить существующие правила в заданной цепочке
—delete -D удалить правило с указанным номером в заданной цепочке
—insert -I вставить правило с заданным номером, без указания номера — правило будет по умолчанию добавлено первым
—replace -R заменить правило с указанным номером
—list -L вывести список всех действующих правил со всех цепочек, если указать интересующую цепочку — вывод будет сделан только по ней
—list-rules -S построчный вывод всех правил во всех цепочках, если после ключа указать имя цепочки — будут выведены только ее правила
—flush -F удалить все правила, при указании имени цепочки — правила удаляться только в ней
—zero -Z обнулить все счетчики во всех цепочках, при указании цепочки — обнуление произойдет только в ней
—new -N создать пользовательскую цепочку
—delete-chain -X удалить пользовательскую цепочку
—policy -P установить политику по умолчанию для цепочки, обычно это ACCEPT или DROP, она будет применена к пакетам, не попавшим ни под один критерий
—rename-chain -E переименовать цепочку, сначала указывается текущее имя, через пробел — новое
—help -h вывести справочную информацию по синтаксису iptables

Критерии

Чтобы к пакету применить какое-либо действие, он должен попасть под определенные критерии. Одно правило может содержать несколько критериев. Они, как и команды, имеют полную и сокращенную форму. Некоторые из них поддерживают логическую НЕ, если перед ними поставить знак ! — критерий будет инвертирован. Список в таблице ниже:

Полный вид Сокращенный вид Поддержка инверсии Описание
—protocol -p да указывает протокол, такие как tcp, udp, udplite и другие, поддерживаемые системой, ознакомиться со списком можно в файле /etc/protocols
—source -s да указывает адрес источника пакета, в качестве значения можно указать как один IP-адрес, так и диапазон
—destination -d да адрес получателя, синтаксис аналогичен предыдущему пункту
—match -m нет подключает указанный модуль
—jump -j нет когда правило подошло — выполнить указанное действие
—goto -g нет перейти к указанной цепочке правил
—in-interface -i да задает входящий сетевой интерфейс
—out-interface -o да указывает исходящий сетевой интерфейс
—fragment -f да указывает на фрагменты фрагментированных пакетов
—set-counters -c нет устанавливает начальные значения счетчиков пакетов и байт
—destination-port —dport да порт получателя пакета
—source-port —sport да порт отправителя пакета

Состояние соединений

Система отслеживания состояния соединений conntrack — важная часть сетевого стека linux, встроенная в ядро. Используется для сопоставления пакетов с конкретными соединениями. Под анализ попадают все пакеты, кроме помеченных NOTRACK, в таблице raw. Все пакеты классифицируются на:

  • NEW — открывается новое соединение, пришел только первый пакет;
  • ESTABLISHED — соединение установлено, пришел уже не первый пакет в рамках этого сеанса. При правильной настройке iptables — такие пакеты проходят по системе без фильтрации, поскольку она уже была выполнена для первого пакета соединения;
  • RELATED — открывается новое соединение, связанное с другим сеансом, имеющим статус ESTABLISHED;
  • INVALID — помечаются пакеты, которые не связаны ни с одним из существующих соединений, и не могут создать новое, их невозможно идентифицировать. В целях безопасности рекомендуется остановить движение таких пакетов по системе, используя действие DROP.

Основные команды iptables

Как посмотреть список правил iptables

Отображать все действующие правила лучше с детализацией и нумерацией строк:

iptables --line-numbers -L -v -n

Ключ —line-numbers нумерует строки, -L выводит список правил всех цепочек, -v отвечает за детализацию вывода, -n выводит IP-адреса и номера портов в числовом формате.

Как удалить правило в iptables

В первую очередь необходимо определить номер правила, которое требуется удалить, выводим список действующих правил командой:

iptables --line-numbers -L -v -n

Вывод:

Chain INPUT (policy ACCEPT 255 packets, 13366 bytes)
num   pkts bytes target     		prot 	opt in     out     source               destination
1            0        0 DROP       	all  	--    *      *       172.10.10.1         0.0.0.0/0
2            0        0 ACCEPT     	all  	--    *      *       192.168.111.1      0.0.0.0/0
3            0        0 ACCEPT     	tcp  	--    *      *        0.0.0.0/0	            0.0.0.0/0           tcp dpt:22
4            1      40 ACCEPT     	tcp  	--    *      *        0.0.0.0/0             0.0.0.0/0            tcp dpt:80
5            1      40 ACCEPT    	tcp  	--    *      *        0.0.0.0/0             0.0.0.0/0            tcp dpt:443

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 256 packets, 15806 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Предположим, требуется удалить правило 4 в цепочке INPUT:

iptables -D INPUT 4

Проверяем:

Chain INPUT (policy ACCEPT 77 packets, 8358 bytes)
num   pkts bytes target     		prot 	opt in     out     source               destination
1            0        0 DROP       	all  	--    *      *       172.10.10.1         0.0.0.0/0
2            0        0 ACCEPT     	all  	--    *      *       192.168.111.1      0.0.0.0/0
3            0      48 ACCEPT     	tcp  	--    *      *        0.0.0.0/0	            0.0.0.0/0           tcp dpt:22
5            1      40 ACCEPT    	tcp  	--    *      *        0.0.0.0/0             0.0.0.0/0            tcp dpt:443

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 82 packets, 11150 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Правило удалено.

Как очистить список правил iptables

Сброс всех правил обычно требуется совместно с изменением политики по умолчанию на ACCEPT, эта процедура связана с вводом набора правил, поэтому удобнее всего создать небольшой скрипт для автоматизации процесса:

nano /etc/iptables.reset

Наполняем его командами:

#!/bin/bash
colGreen="\033[32m"
resetCol="\033[0m"
echo -n "Flushing firewall rules and changing default policy to ACCEPT..."
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
echo -e "$colGreen Done! $resetCol"

Сохраняем и выходим. Команды можно последовательно подавать вручную, но это замедляет работу и увеличивает риск ошибки за счет влияния человеческого фактора.

Делаем файл исполняемым:

chmod +x /etc/iptables.reset

Даем команду:

/etc/iptables.reset

Правила сброшены, применяется политика по умолчанию ACCEPT для всех цепочек. Нередко случается, что при написании правил теряется доступ к серверу из-за допущенных ошибок в созданных правилах. Работая с облачной платформой Selectel, это не проблема. Не нужно ждать, когда кто-то перезагрузит сервер и все починит. Все делается в панели управления, быстро и удобно. В меню слева, нажимаем Облачная платформа, справа отобразится список серверов, нажимаем на значок «Консоль» напротив имени машины, доступ к которой прекратился.

В открывшейся консоли необходимо авторизоваться, после ввести команду, если скрипт был ранее подготовлен:

/etc/iptables.reset

Если скрипт не был создан, то ввести команды последовательно.

Доступ восстановлен.

Как сохранить правила iptables

Утилита iptables, как и маршрутизаторы Cisco, не сохраняет правила, если это явно не указать и после перезагрузки возвращается в предыдущее состояние. Установим пакет:

apt install iptables-persistent

В процессе установки на оба вопроса ответить Yes. Сохранить текущие правила:

service netfilter-persistent save

Система при следующей загрузке использует последние сохраненные правила.

Как восстановить правила

В процессе настройки брандмауэра, по разным причинам, возникает необходимость вернуться к заведомо рабочим, испытанным правилам. Сервис netfilter-persistent сохраняет их в файле /etc/iptables/rules.v4, если не успели сохранить активные правила, значит в файле предыдущая версия, восстанавливаем:

iptables-restore < /etc/iptables/rules.v4

Как записать в лог событие

В процессе отладки правил, требуется фиксировать события в системном журнале. Запретим входящие пакеты на порт 80:

iptables -A INPUT -p tcp --dport 80 -j LOG --log-prefix "ACCESS RESTRICTED: "
iptables -A INPUT -p tcp --dport 80 -j DROP

Убедимся, что записи событий ведутся. Откроем файл журнала:

nano /var/log/syslog

В нем должны быть строки вида:

Apr 11 23:18:11 localhost kernel: [20400.047777] ACCESS RESTRICTED: IN=eth0 OUT= MAC=xx:yy:zz:xx:yy:zz:xx:yy:zz:xx:yy:zz:xx:yy SRC=111.222.121.212 DST=192.168.0.2 LEN=44 TOS=0x00 PREC=0x00 TTL=55 ID=49410 DF PROTO=TCP SPT=49170 DPT=80 WINDOW=65535 RES=0x00 SYN URGP=0

Примеры настройки iptables

В данном разделе рассмотрим задачи, с которыми придется столкнуться, работая с iptables.

Как заблокировать IP-адрес в iptables

Допустим, необходимо заблокировать компьютер с IP-адресом 172.10.10.1, тогда правило будет выглядеть следующим образом:

iptables -A INPUT -s 172.10.10.1 -j DROP

Как разрешить IP-адрес в iptables

Необходимо разрешить весь трафик к серверу для клиента с IP-адресом 192.168.111.1:

iptables -A INPUT -s 192.168.111.1 -j ACCEPT

Как открыть порт в iptables

Предположим, что политика по умолчанию — блокировать все, что явно не разрешено. Откроем порты веб-сервера для обеспечения работы HTTP протокола — порт 80, и поддержки HTTPS протокола совместно с SSL — порт 443. Также для доступа к серверу по SSH откроем порт 22. Эту задачу можно решить как минимум двумя способами: создать однострочное правило, либо прописать правила по каждому из портов, рассмотрим оба. В одну строку:

iptables -A INPUT -p tcp -m multiport --dports 22,80,443 -j ACCEPT

При использовании расширения multiport, всегда необходимо использовать критерий -p tcp или -p udp, таким образом, одной строкой можно указать до 15 разных портов через запятую. Важно не путать критерии —-dport и —-dports. Первый из них используется для указания одного порта, второй сразу для нескольких, аналогично с —sport и —sports.

Вариант многострочной записи — для каждого порта свое правило:

iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

Как закрыть порт в iptables

Необходимость в закрытии порта может возникнуть, когда используется политика по умолчанию ACCEPT и доступ к определенному сервису нужно ограничить. Рассмотрим несколько ситуаций.

Закроем доступ к FTP серверу, работающему на 21 порту:

iptables -A INPUT -p tcp --dport 21 -j DROP

Оставим доступ только себе к SSH серверу, для остальных запретим:

iptables -A INPUT -p tcp ! -s 192.168.124.5 --dport 22 -j DROP

Здесь 192.168.124.5 — IP-адрес доверенной машины, знак ! перед ключом -s используется для инверсии, т.е. всем, кроме этого адреса доступ закрыт.

Как разрешить или запретить ICMP ping трафик

Разрешить ping хоста:

iptables -A INPUT -p icmp --icmp-type 8 -j ACCEPT

Запретить входящие icmp-пакеты:

iptables -A INPUT -p icmp --icmp-type 8 -j DROP

Как разрешить трафик на локальном узле

Трафик на локальном сетевом интерфейсе lo должен быть разрешен для корректной работы сервисов, использующих для обмена данными интерфейс локальной петли, например, базы данных, прокси-сервер squid. Поэтому рекомендуется разрешить трафик на вход и выход:

iptables -A INPUT -i lo -j ACCEPT 
iptables -A OUTPUT -o lo -j ACCEPT

Как блокировать трафик по MAC-адресу

Устройство, которому хотим запретить доступ к серверу, имеет MAC-адрес 00:0A:EF:76:23:12:

iptables -A INPUT -m mac --mac-source 00:0A:EF:76:23:12 -j DROP

Здесь ключ -m вызывает расширение mac, ключ —mac-source задает MAC-адрес узла, с которого поступил пакет.

Как разрешить трафик по MAC-адресу

Необходимость может возникнуть в случае использования политики запрещения всего, что явно не разрешено, на практике редко встречается разрешение по MAC-адресам, команда iptables имеет вид:

iptables -A INPUT -m mac --mac-source 00:0A:EF:76:23:12 -j ACCEPT

Как ограничить доступ по времени

В iptables существует модуль time, который позволяет регулировать доступ согласно расписанию. Например, запретим доступ к FTP серверу в среду с 08:10 до 08:15:

iptables -I INPUT -p tcp --dport 21 -m time --kerneltz --timestart 08:10 --timestop 08:15 --weekdays We --syn -j DROP

Рассмотрим подробнее значения ключей:

  • —kerneltz — использование времени текущей временной зоны, иначе iptables будет работать по времени часового пояса UTC;
  • —timestart — время начала срабатывания условия, допустимый диапазон указания времени с 00:00:00 до 23:59:59, можно указывать время в коротком варианте ЧЧ:ММ, как это сделано в примере;
  • —timestop — время окончания действия условия, формат ввода аналогичен timestart;
  • —weekdays — дни недели, в которые условие будет работать, допустимые значения Mon, Tue, Wed, Thu, Fri, Sat, Sun, или значения от 1 до 7. Так же поддерживается формат в два символа, например Mo, Tu, We и т.д. При необходимости указать несколько дней — перечисляются через запятую, без пробела, например Fr,Su,We,Tu;
  • —monthdays — задает день месяца, допустимые значения от 1 до 31.

Настройка NAT

Преобразование сетевых адресов (от англ. Network Address Translation) используется на маршрутизаторах, для взаимного предоставления сервисов между сетями согласно определенным правилам. В iptables для этого предусмотрена таблица nat, для которой характерны действия DNAT, SNAT, MASQUERADE, каждое из них описано в начале статьи. Рассмотрим практические задачи.

Проброс порта

Дано: локальная сеть на основе облачной платформы Selectel, состоящая из двух серверов и маршрутизатора с публичным IP-адресом.

Оба сервера имеют доступ в Интернет, но только один, используемый в качестве брандмауэра, — имеет публичный IP-адрес. Наглядная схема на иллюстрации ниже.

Это означает, что все пакеты, приходящие на публичный IP-адрес, доставляются сразу на компьютер с IP-адресом 192.168.0.2.

Задача: Предоставить доступ снаружи к веб-серверу с IP-адресом 192.168.0.3.

Решение: Все операции с iptables выполняются на сервере 192.168.0.2. В схеме получается два маршрутизатора. При запросе пользователем веб-страницы — пакет с маршрутизатора, который имеет публичный адрес, попадает на сервер-маршрутизатор 192.168.0.2, на порт 80, нужно его передать веб-серверу 192.168.0.3. Делаем первый шаг — меняем адрес назначения пакета:

iptables -t nat -A PREROUTING -p tcp -d 192.168.0.2 --dport 80 -j DNAT --to-destination 192.168.0.3:80

DNAT используется, если необходимо пользователям глобальной сети предоставить доступ к компьютеру, находящемуся за маршрутизатором, т.е. во внутренней сети, это называется пробросом портов.

Теперь нужно поменять адрес отправителя пакета на адрес маршрутизатора 192.168.0.2, который передаст пакет маршрутизатору с публичным IP-адресом, а он уже в свою очередь доставит пакет клиенту, используем для этого SNAT. Делаем второй шаг:

iptables -t nat -A POSTROUTING -p tcp -d 192.168.0.3 --dport 80 -j SNAT --to-source 192.168.0.2

Та же самая команда при использовании действия MASQUERADE не потребует ключа —to-source и указания адреса, поскольку в таком случае происходит автоматическая подмена адреса отправления на IP-адрес сетевого интерфейса, с которого ушел пакет:

iptables -t nat -A POSTROUTING -p tcp -d 192.168.0.3 --dport 80 -j MASQUERADE

Проброс порта веб-сервера выполнен.

Переадресация порта — redirect

Перенаправление пакетов, пришедших на один порт, другому порту, называют переадресацией. В качестве примера — предварительно настроим веб-сервер на работу с портом 8080, добавим следующие правила:

iptables -A INPUT -p tcp --dport 8080 -j ACCEPT
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080

Действие REDIRECT выполняется в пределах одного сервера и имеет единственный ключ —-to-ports, указывающий порт назначения, этот ключ разрешается использовать, если критерий -p явно задает используемый протокол tcp или udp.

Использование в качестве маршрутизатора

Рассмотрим классическую схему для выхода в Интернет в рамках типового офиса. Имеется несколько компьютеров, которым надо предоставить доступ в глобальную сеть, один канал в Интернет, шлюз на основе компьютера c двумя сетевыми картами и операционной системой Linux.

Задача маршрутизатора не только предоставить доступ в Интернет, но еще и сделать это безопасно. Одна сетевая карта подключена в локальную сеть, по умолчанию будем считать доверенной зоной, другой сетевой адаптер с постоянным адресом подключен к сети Интернет. Схема подключения для наглядности:

Создадим файл:

touch /etc/iptables.router

Откроем, например, редактором nano:

nano /etc/iptables.router

Ниже представлен набор правил iptables с комментариями, для реализации данной схемы, копируем эти строки в открытый файл:

#!/bin/bash
# Объявление переменных
export FW="iptables"
# Интерфейс, подключенный к локальной сети
LAN="enp16s0"
# Интерфейс, подключенный к Интернету
WAN="enp0s25"
# Диапазон адресов локальной сети
LAN_NET="192.168.30.0/24"

# Очистка всех цепочек и удаление правил
$FW -F
$FW -F -t nat
$FW -F -t mangle
$FW -X
$FW -t nat -X
$FW -t mangle -X

# Разрешить входящий трафик к интерфейсу локальной петли,
# это необходимо для корректной работы некоторых сервисов
$FW -A INPUT -i lo -j ACCEPT

# Разрешить на внутреннем интерфейсе весь трафик из локальной сети
$FW -A INPUT -i $LAN -s $LAN_NET -j ACCEPT

# Позволяем два, наиболее безопасных типа пинга
$FW -A INPUT -p icmp --icmp-type 0 -j ACCEPT
$FW -A INPUT -p icmp --icmp-type 8 -j ACCEPT

# Разрешить входящие соединения, которые были разрешены в рамках других соединений
$FW -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

# Разрешить перенаправление трафика с внутренней сети наружу, как для новых,
# так и уже имеющихся соединений в системе
$FW -A FORWARD -i $LAN -o $WAN -m conntrack --ctstate NEW,RELATED,ESTABLISHED -j ACCEPT

# Разрешить перенаправление только тех пакетов с внешней сети внутрь,
# которые уже являются частью имеющихся соединений
$FW -A FORWARD -i $WAN -o $LAN -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

# Выполняем трансляцию сетевых адресов, принадлежащих локальной сети
$FW -t nat -A POSTROUTING -o $WAN -s $LAN_NET -j MASQUERADE

# Устанавливаем политики по умолчанию:
# Входящий трафик — сбрасывать; Проходящий трафик — сбрасывать; Исходящий — разрешать
$FW -P INPUT DROP
$FW -P FORWARD DROP
$FW -P OUTPUT ACCEPT

Важное замечание. Данный набор правил — это примитивный маршрутизатор, частный случай, представлен для наглядности и не претендует на руководство по безопасности. Поэтому, каждому, кто будет копировать, необходимо изменить его под свои нужды, как минимум переменные LAN, WAN и LAN_NET.

Сохраняем файл сочетанием нажатий клавиш Ctrl+O, нажимаем ENTER для подтверждения, затем Ctrl+X для выхода. Делаем файл исполняемым:

chmod +x /etc/iptables.router

Активируем правила, выполнив подготовленный файл скрипта:

/etc/iptables.router

Включаем маршрутизацию пакетов в системе:

sysctl -w net.ipv4.ip_forward=1

Чтобы после перезагрузки маршрутизация заработала автоматически — нужно добавить в файл /etc/sysctl.conf строку или привести уже имеющуюся к виду:

net.ipv4.ip_forward = 1

Осталось сохранить правила iptables:

service netfilter-persistent save

Доступ в Интернет предоставлен.

Contents

  1. Basic iptables howto
  2. Basic Commands
  3. Basic Iptables Options
  4. Allowing Established Sessions
  5. Allowing Incoming Traffic on Specific Ports
  6. Blocking Traffic
  7. Editing iptables
  8. Logging
  9. Saving iptables
  10. Configuration on startup

    1. Solution #1 — /etc/network/interfaces
    2. Solution #2 /etc/network/if-pre-up.d and ../if-post-down.d
    3. Solution #3 iptables-persistent
  11. Configuration on Startup for NetworkManager
  12. Tips

    1. If you manually edit iptables on a regular basis
    2. Using iptables-save/restore to test rules
    3. More detailed Logging
    4. Disabling the firewall
  13. Easy configuration via GUI

    1. UFW & GUFW
  14. Further Information
  15. Credits

Basic iptables howto

Iptables is a firewall, installed by default on all official Ubuntu distributions (Ubuntu, Kubuntu, Xubuntu). When you install Ubuntu, iptables is there, but it allows all traffic by default. Ubuntu comes with ufw — a program for managing the iptables firewall easily.

There is a wealth of information available about iptables, but much of it is fairly complex, and if you want to do a few basic things, this How To is for you.

Basic Commands

Typing

sudo iptables -L

lists your current rules in iptables. If you have just set up your server, you will have no rules, and you should see

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Basic Iptables Options

Here are explanations for some of the iptables options you will see in this tutorial. Don’t worry about understanding everything here now, but remember to come back and look at this list as you encounter new options later on.

  • -A — Append this rule to a rule chain. Valid chains for what we’re doing are INPUT, FORWARD and OUTPUT, but we mostly deal with INPUT in this tutorial, which affects only incoming traffic.

  • -L — List the current filter rules.

  • -m conntrack — Allow filter rules to match based on connection state. Permits the use of the —ctstate option.

  • —ctstate — Define the list of states for the rule to match on. Valid states are:

    • NEW — The connection has not yet been seen.
    • RELATED — The connection is new, but is related to another connection already permitted.
    • ESTABLISHED — The connection is already established.
    • INVALID — The traffic couldn’t be identified for some reason.
  • -m limit — Require the rule to match only a limited number of times. Allows the use of the —limit option. Useful for limiting logging rules.

    • —limit — The maximum matching rate, given as a number followed by «/second», «/minute», «/hour», or «/day» depending on how often you want the rule to match. If this option is not used and -m limit is used, the default is «3/hour».

  • -p — The connection protocol used.

  • —dport — The destination port(s) required for this rule. A single port may be given, or a range may be given as start:end, which will match all ports from start to end, inclusive.

  • -j — Jump to the specified target. By default, iptables allows four targets:

    • ACCEPT — Accept the packet and stop processing rules in this chain.

    • REJECT — Reject the packet and notify the sender that we did so, and stop processing rules in this chain.

    • DROP — Silently ignore the packet, and stop processing rules in this chain.

    • LOG — Log the packet, and continue processing more rules in this chain. Allows the use of the —log-prefix and —log-level options.

  • —log-prefix — When logging, put this text before the log message. Use double quotes around the text to use.

  • —log-level — Log using the specified syslog level. 7 is a good choice unless you specifically need something else.

  • -i — Only match if the packet is coming in on the specified interface.

  • -I — Inserts a rule. Takes two options, the chain to insert the rule into, and the rule number it should be.

    • -I INPUT 5 would insert the rule into the INPUT chain and make it the 5th rule in the list.

  • -v — Display more information in the output. Useful for if you have rules that look similar without using -v.

  • -s —source — address[/mask] source specification

  • -d —destination — address[/mask] destination specification

  • -o —out-interface — output name[+] network interface name ([+] for wildcard)

Allowing Established Sessions

We can allow established sessions to receive traffic:

sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
  • The above rule has no spaces either side of the comma in ESTABLISHED,RELATED

If the line above doesn’t work, you may be on a castrated VPS whose provider has not made available the extension, in which case an inferior version can be used as last resort:

sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Allowing Incoming Traffic on Specific Ports

You could start by blocking traffic, but you might be working over SSH, where you would need to allow SSH before blocking everything else.

To allow incoming traffic on the default SSH port (22), you could tell iptables to allow all TCP traffic on that port to come in.

sudo iptables -A INPUT -p tcp --dport ssh -j ACCEPT

Referring back to the list above, you can see that this tells iptables:

  • append this rule to the input chain (-A INPUT) so we look at incoming traffic
  • check to see if it is TCP (-p tcp).
  • if so, check to see if the input goes to the SSH port (—dport ssh).
  • if so, accept the input (-j ACCEPT).

Lets check the rules: (only the first few lines shown, you will see more)

sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh

Now, let’s allow all incoming web traffic

sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT

Checking our rules, we have

sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:www

We have specifically allowed tcp traffic to the ssh and web ports, but as we have not blocked anything, all traffic can still come in.

Blocking Traffic

Once a decision is made to accept a packet, no more rules affect it. As our rules allowing ssh and web traffic come first, as long as our rule to block all traffic comes after them, we can still accept the traffic we want. All we need to do is put the rule to block all traffic at the end.

sudo iptables -A INPUT -j DROP
sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:www
DROP       all  --  anywhere             anywhere

Because we didn’t specify an interface or a protocol, any traffic for any port on any interface is blocked, except for web and ssh.

Editing iptables

The only problem with our setup so far is that even the loopback port is blocked. We could have written the drop rule for just eth0 by specifying -i eth0, but we could also add a rule for the loopback. If we append this rule, it will come too late — after all the traffic has been dropped. We need to insert this rule before that. Since this is a lot of traffic, we’ll insert it as the first rule so it’s processed first.

sudo iptables -I INPUT 1 -i lo -j ACCEPT
sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:www
DROP       all  --  anywhere             anywhere

The first and last lines look nearly the same, so we will list iptables in greater detail.

sudo iptables -L -v
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination         
    0     0 ACCEPT     all  --  lo     any     anywhere             anywhere
    0     0 ACCEPT     all  --  any    any     anywhere             anywhere            state RELATED,ESTABLISHED
    0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere            tcp dpt:ssh
    0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere            tcp dpt:www
    0     0 DROP       all  --  any    any     anywhere             anywhere

You can now see a lot more information. This rule is actually very important, since many programs use the loopback interface to communicate with each other. If you don’t allow them to talk, you could break those programs!

Logging

In the above examples none of the traffic will be logged. If you would like to log dropped packets to syslog, this would be the quickest way:

sudo iptables -I INPUT 5 -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7

See Tips section for more ideas on logging.

Saving iptables

If you were to reboot your machine right now, your iptables configuration would disappear. Rather than type this each time you reboot, however, you can save the configuration, and have it start up automatically. To save the configuration, you can use iptables-save and iptables-restore.

Configuration on startup

WARNING: Iptables and NetworkManager can conflict. Also if you are concerned enough about security to install a firewall you might not want to trust NetworkManager. Also note NetworkManager and iptables have opposite aims. Iptables aims to keep any questionable network traffic out. NetworkManager aims to keep you connected at all times. Therefore if you want security all the time, run iptables at boot time. If you want security some of the time then NetworkManager might be the right choice.

WARNING: If you use NetworkManager (installed by default on Feisty and later) these steps will leave you unable to use NetworkManager for the interfaces you modify. Please follow the steps in the next section instead.

NOTE: It appears on Hardy, NetworkManager has an issue with properly on saving and restoring the iptable rules when using the method in the next section. Using this first method appears to work. If you find otherwise, please update this note.

Save your firewall rules to a file

sudo sh -c "iptables-save > /etc/iptables.rules"

At this point you have several options. You can make changes to /etc/network/interfaces or add scripts to /etc/network/if-pre-up.d/ and /etc/network/if-post-down.d/ to achieve similar ends. The script solution allows for slightly more flexibility.

Solution #1 — /etc/network/interfaces

(NB: be careful — entering incorrect configuration directives into the interface file could disable all interfaces, potentially locking you out of a remote machine.)

Modify the /etc/network/interfaces configuration file to apply the rules automatically. You will need to know the interface that you are using in order to apply the rules — if you do not know, you are probably using the interface eth0, although you should check with the following command first to see if there are any wireless cards:

iwconfig

If you get output similar to the following, then you do not have any wireless cards at all and your best bet is probably eth0.

lo        no wireless extensions.

eth0      no wireless extensions.

When you have found out the interface you are using, edit (using sudo) your /etc/network/interfaces:

sudo nano /etc/network/interfaces

When in the file, search for the interface you found, and at the end of the network related lines for that interface, add the line:

pre-up iptables-restore < /etc/iptables.rules

You can also prepare a set of down rules, save them into second file /etc/iptables.downrules and apply it automatically using the above steps:

post-down iptables-restore < /etc/iptables.downrules

A fully working example using both from above:

auto eth0
iface eth0 inet dhcp
  pre-up iptables-restore < /etc/iptables.rules
  post-down iptables-restore < /etc/iptables.downrules

You may also want to keep information from byte and packet counters.

sudo sh -c "iptables-save -c > /etc/iptables.rules" 

The above command will save the whole rule-set to a file called /etc/iptables.rules with byte and packet counters still intact.

Solution #2 /etc/network/if-pre-up.d and ../if-post-down.d

NOTE: This solution uses iptables-save -c to save the counters. Just remove the -c to only save the rules.

Alternatively you could add the iptables-restore and iptables-save to the if-pre-up.d and if-post-down.d directories in the /etc/network directory instead of modifying /etc/network/interface directly.

NOTE: Scripts in if-pre-up.d and if-post-down.d must not contain dot in their names.

The script /etc/network/if-pre-up.d/iptablesload will contain:

#!/bin/sh
iptables-restore < /etc/iptables.rules
exit 0

and /etc/network/if-post-down.d/iptablessave will contain:

#!/bin/sh
iptables-save -c > /etc/iptables.rules
if [ -f /etc/iptables.downrules ]; then
   iptables-restore < /etc/iptables.downrules
fi
exit 0

Then be sure to give both scripts execute permissions:

sudo chmod +x /etc/network/if-post-down.d/iptablessave
sudo chmod +x /etc/network/if-pre-up.d/iptablesload

Solution #3 iptables-persistent

Install and use the iptables-persistent package.

Configuration on Startup for NetworkManager

NetworkManager includes the ability to run scripts when it activates or deactivates an interface. To save iptables rules on shutdown, and to restore them on startup, we are going to create such a script. To begin, press Alt+F2 and enter this command:

For Ubuntu:

gksudo gedit /etc/NetworkManager/dispatcher.d/01firewall

For Kubuntu:

kdesu kate /etc/NetworkManager/dispatcher.d/01firewall

Then, paste this script into your editor, save, and exit the editor.

if [ -x /usr/bin/logger ]; then
        LOGGER="/usr/bin/logger -s -p daemon.info -t FirewallHandler"
else
        LOGGER=echo
fi

case "$2" in
        up)
                if [ ! -r /etc/iptables.rules ]; then
                        ${LOGGER} "No iptables rules exist to restore."
                        return
                fi
                if [ ! -x /sbin/iptables-restore ]; then
                        ${LOGGER} "No program exists to restore iptables rules."
                        return
                fi
                ${LOGGER} "Restoring iptables rules"
                /sbin/iptables-restore -c < /etc/iptables.rules
                ;;
        down)
                if [ ! -x /sbin/iptables-save ]; then
                        ${LOGGER} "No program exists to save iptables rules."
                        return
                fi
                ${LOGGER} "Saving iptables rules."
                /sbin/iptables-save -c > /etc/iptables.rules
                ;;
        *)
                ;;
esac

Finally, we need to make sure NetworkManager can execute this script. In a terminal window, enter this command:

sudo chmod +x /etc/NetworkManager/dispatcher.d/01firewall

Tips

If you manually edit iptables on a regular basis

The above steps go over how to setup your firewall rules and presume they will be relatively static (and for most people they should be). But if you do a lot of development work, you may want to have your iptables saved everytime you reboot. You could add a line like this one in /etc/network/interfaces:

  pre-up iptables-restore < /etc/iptables.rules
  post-down iptables-save > /etc/iptables.rules

The line «post-down iptables-save > /etc/iptables.rules» will save the rules to be used on the next boot.

Using iptables-save/restore to test rules

If you edit your iptables beyond this tutorial, you may want to use the iptables-save and iptables-restore feature to edit and test your rules. To do this open the rules file in your favorite text editor (in this example gedit).

sudo sh -c "iptables-save > /etc/iptables.rules"
gksudo gedit /etc/iptables.rules

You will have a file that appears similiar to (following the example above):

# Generated by iptables-save v1.3.1 on Sun Apr 23 06:19:53 2006
*filter
:INPUT ACCEPT [368:102354]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [92952:20764374]
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
-A INPUT -j DROP
COMMIT
# Completed on Sun Apr 23 06:19:53 2006

Notice that these are iptables commands minus the iptable command. Feel free to edit this to file and save when complete. Then to test simply:

sudo iptables-restore < /etc/iptables.rules

NOTE: With iptables 1.4.1.1-1 and above, a script allow you to test your new rules without risking to brick your remote server. If you are applying the rules on a remote server, you should consider testing it with:

sudo iptables-apply /etc/iptables.rules

After testing, if you have not added the iptables-save command above to your /etc/network/interfaces remember not to lose your changes:

sudo sh -c "iptables-save > /etc/iptables.rules"

More detailed Logging

For further detail in your syslog you may want create an additional Chain. This will be a very brief example of my /etc/iptables.rules showing how I setup my iptables to log to syslog:

# Generated by iptables-save v1.3.1 on Sun Apr 23 05:32:09 2006
*filter
:INPUT ACCEPT [273:55355]
:FORWARD ACCEPT [0:0]
:LOGNDROP - [0:0]
:OUTPUT ACCEPT [92376:20668252]
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -j LOGNDROP
-A LOGNDROP -p tcp -m limit --limit 5/min -j LOG --log-prefix "Denied TCP: " --log-level 7
-A LOGNDROP -p udp -m limit --limit 5/min -j LOG --log-prefix "Denied UDP: " --log-level 7
-A LOGNDROP -p icmp -m limit --limit 5/min -j LOG --log-prefix "Denied ICMP: " --log-level 7
-A LOGNDROP -j DROP
COMMIT
# Completed on Sun Apr 23 05:32:09 2006

Note a new CHAIN called LOGNDROP at the top of the file. Also, the standard DROP at the bottom of the INPUT chain is replaced with LOGNDROP and add protocol descriptions so it makes sense looking at the log. Lastly we drop the traffic at the end of the LOGNDROP chain. The following gives some idea of what is happening:

  • —limit sets the number of times to log the same rule to syslog

  • —log-prefix «Denied…» adds a prefix to make finding in the syslog easier

  • —log-level 7 sets the syslog level to informational (see man syslog for more detail, but you can probably leave this)

Disabling the firewall

If you need to disable the firewall temporarily, you can flush all the rules using

sudo iptables -P INPUT ACCEPT
sudo iptables -P OUTPUT ACCEPT
sudo iptables -P FORWARD ACCEPT
sudo iptables -F

or create a script using text editor such as nano

sudo nano -w /root/fw.stop
echo "Stopping firewall and allowing everyone..."
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

Make sure you can execute the script

sudo chmod +x /root/fw.stop

You can run the script

sudo /root/fw.stop

Easy configuration via GUI

UFW & GUFW

GUFW — Gufw is a graphical frontend to UFW (Uncomplicated Firewall).

Further Information

Iptables Tutorial

Iptables How To

Netfilter and Iptables Multilingual Documentation

Easy Firewall Generator for IPTables

Shoreline Firewall, a.k.a. Shorewall, is a firewall generator for iptables which allows advanced configuration with simple configuration files. It is available from the Ubuntu repositories via apt-get.

Credits

Thanks to Rusty Russell and his How-To, as much of this is based off that.


CategorySecurity

Понравилась статья? Поделить с друзьями:
  • Руководства для технических писателей
  • Что необходимо для процедуры банкротства физического лица пошаговая инструкция
  • Как заверить копию должностной инструкции образец
  • Full size starlight night vision инструкция
  • Мануалы по ремонту двигателей скачать бесплатно