Руководство по настройки 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.
Iptables – это стандартный файрвол, поставляемый в большинство дистрибутивов Linux по умолчанию. В предыдущей статье мы рассмотрели основные определения и принцип работы iptables, понимание которых обязательно для практического использования инструмента. В данной статье мы изучим основные команды файрвола и напишем наши первые правила.
Замечание:
Для создания правил iptables нам потребуется возможность выполнения команд с повышением привилегий до суперпользователя root. Поэтому для настройки межсетевого экрана нужно зайти в систему под учетной записью root (что не является лучшей практикой с точки зрения безопасности), либо использовать команду sudo перед каждой командой настройки iptables для повышения привилегий пользователя. Мы будем применять второй вариант.

Основные команды iptables

Вывод текущих правил в табличном виде выполняется при помощи вызова команды iptables с ключом -L:

Вывод:

Output:
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

В выводе представлены 3 стандартных цепочки (INPUT, OUTPUT, FORWARD) и действие по умолчанию (default policy) для каждой цепочки – ACCEPT. Как видим, у нас пока нет боевых правил. По умолчанию iptables идет без предустановленных правил и пропускает весь трафик.
Вывод текущих настроенных правил в виде строк выполняется при помощи вызова команды iptables с ключом -S:

sudo iptables -S

Более подробно

Вывод:

Output:
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT

Ключ -P указывает на действие, применяемое к пакету по умолчанию.
Построчный вывод полезен тем, что каждая строка вывода — это полноценная команда в iptables (например, мы можем получить такой вывод уже на настроенном сервере и использовать его для настройки другого сервера, сделав небольшие правки).
Для очистки всех правил используется ключ -F:

sudo iptables -F

Тут стоит отметить важность политик по умолчанию, так как они не удалятся после применения этой команды. Поясним подробней. Допустим у нас есть только удаленный доступ к серверу и в политике iptables по умолчанию выставлено действие DROP. В результате чего после очистки всех правил повторное подключение к серверу будет невозможно. Поэтому, если у нас нет физического доступа или консольного подключения к серверу, то перед сбросом всех правил необходимо убедиться, что действие по умолчанию – ACCEPT. Это позволит нам удаленно подключиться к серверу, создать разрешающее удаленную сессию первое правило. После этого для повышения безопасности можно уже выставить политику по умолчанию – DROP.
Чтобы задать действие по умолчанию ACCEPT и выполнить последующую очистку правил вводим:

sudo iptables -P INPUT ACCEPT
sudo iptables -P OUTPUT ACCEPT
sudo iptables -F

Создание первого правила iptables

Это будет правило, о котором мы говорили выше. Оно позволит принимать текущее SSH-соединение между нами и сервером. Синтаксис команды, добавляющей это правило, следующий:

sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED, RELATED -j ACCEPT

На первый взгляд выглядит запутанно. Разберем подробней команду:

  • -A INPUT: флаг -A (append) – добавляет правило в конец цепочки INPUT
  • -m conntrack: этот параметр вызывает модуль conntrack для отслеживания информации о соединениях.
  • –ctstate ESTABLISHED, RELATED: выделяем все соединения в состоянии ESTABLISHED (выделяется трафик по уже существующим соединениям) и RELATED (трафик по новым соединениям, но связанных с уже открытыми).
  • -j ACCEPT: действие (target) – то, что будет произведено с пакетом, если он попал под критерий. В нашем случае это ACCEPT.

После применения этого правила можем увидеть изменения в выводе:

sudo iptables -L
Output:
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHED

Chain FORWARD (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

Теперь мы можем менять действия в политике по умолчанию на DROP.

Другие правила iptables

Добавим еще два правила, разрешающие SSH-соединения (по умолчанию на 22 порт) и WEB-подключения на 80 порт.
Приведем синтаксис этих правил:

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

Разберем новые параметры:

  • -p tcp: фильтруем пакеты, использующие протокол TCP
  • –dport: выделяем TCP-пакеты с портом назначения 22 и 80.

Также есть еще одно правило, которое связано с понятием “петли” (loopback-интерфейса). Используется loopback-интерфейс для взаимодействия служб и приложений в пределах одной локальной системы, без надобности отправления пакетов на сетевой интерфейс.
Правило выглядит так:

sudo iptables -I INPUT 1 -i lo -j ACCEPT

Разберем его:

  • Ключ -I (insert) указывает вставить правило в цепочку на 1-ое место. Порядковый номер вставки указывается за именем цепочки INPUT (напоминаем, что флаг -A добавляет правило в конец)
  • -i lo – указываем интерфейс loopback и разрешаем трафик через него.

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

  1. Политика запрета по умолчанию.

Достигается написанием правила:

sudo iptables -P INPUT DROP

Тут надо помнить об опасности потери удаленного доступа к серверу. Желательно его применять, когда есть консольный доступ к серверу.

  1. Добавление запрещающего правила в конец цепочки.
sudo iptables -A INPUT -j DROP

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

sudo iptables -D INPUT -j DROP
sudo iptables -A INPUT "MY_NEW_RULE"
sudo iptables -A INPUT -j DROP

Также можно вставить новое правило до запрещающего правила, используя порядковый номер. Для этого сперва узнаем нумерацию имеющихся правил:

sudo iptables -L --line-numbers

Потом на основании вывода вставляем правило под нужным порядковым номером:

sudo iptables -I INPUT 4 "MY_NEW_RULE"

Более подробно о том как читать и удалять правила в iptables читайте в этой статье.

Сохранение правил iptables

По умолчанию правила iptables не хранятся в постоянной памяти и сбрасываются после перезагрузки. С одной стороны это может быть удобно, в случае потери SSH-подключения к серверу. С другой — часто важна автоматическая загрузка составленных правил после перезагрузки сервера. Один из способов сохранения правил — использование пакета iptables-persistent.
Он стандартно устанавливается из репозиториев Ubuntu:

sudo apt-get update
sudo apt-get install iptables-persistent

Во время установки iptables-persistent попросит подтверждение о сохранении имеющихся правил. Если в последующем мы изменили или добавили правила, то сохраняем их:

sudo invoke-rc.d iptables-persistent save

Вывод

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

Настройка netfilter с помощью iptables

Обновлено Обновлено: 16.12.2022
Опубликовано Опубликовано: 22.02.2017

Утилита командной строки iptables используется для настройки брандмауэра netfilter, встроенного в систему на базе ядра Linux.

Данная инструкция подходит как для чайников, которые хотят разбираться в аспектах защиты сети, так и опытных специалистов в качестве шпаргалки.

Общий синтаксис
Ключи
Примеры
    Общие команды
    Разрешить все
    Работа с простыми правилами
    Проброс портов
    Стартовая настройка
    Сброс на стандартные настройки
Сохранение правил
Использование в Ubuntu и CentOS

Принцип настройки

Общий синтаксис использования iptables:

iptables -t <таблица> <команда> <цепочка> [номер] <условие> <действие>

<таблица>

Правила netfilter распределены по 4-м таблицам, каждая из которых имеет свое назначение (подробнее ниже). Она указывается ключом -t, но если данный параметр не указан, действие будет выполняться для таблицы по умолчанию — filter.

<команда>

Команды указывают, какое именно действие мы совершаем над netfilter, например, создаем или удаляем правило.

<цепочка>

В каждой таблице есть цепочки, для каждой из которых создаются сами правила. Например, для вышеупомянутой таблицы filter есть три предопределенные цепочки — INPUT (входящие пакеты), OUTPUT (исходящие) и FORWARD (транзитные).

[номер]

Некоторые команды требуют указания номера правила, например, на удаление или редактирование.

<условие>

Условие описывает критерии отработки того или иного правила.

<действие>

Ну и, собственно, что делаем с пакетом, если он подходит под критерии условия.

* справедливости ради, стоит отметить, что ключ с действием не обязан идти в конце. Просто данный формат чаще всего встречается в инструкциях и упрощает чтение правил.
 

Для работы с таблицами (iptables -t)

Напоминаю, все правила в netfilter распределены по таблицам. Чтобы работать с конкретной таблицей, необходимо использовать ключ -t.

Ключ Описание
-t filter Таблица по умолчанию. С ней работаем, если упускаем ключ -t. Встроены три цепочки — INPUT (входящие), OUTPUT (исходящие) и FORWARD (проходящие пакеты)
-t nat Для пакетов, устанавливающий новое соединение. По умолчанию, встроены три цепочки — PREROUTING (изменение входящих), OUTPUT (изменение локальных пакетов перед отправкой) и POSTROUTING (изменение всех исходящих).
-t mangle Для изменения пакетов. Цепочки — INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING.
-t raw Для создания исключений в слежении за соединениями. Цепочки: PREROUTING, OUTPUT.

Команды

Нижеперечисленные ключи определяют действия, которые выполняет утилита iptables.

Ключ Описание и примеры
-A Добавление правила в конец списка:
iptables -A INPUT -s 192.168.0.15 -j DROP
запретить входящие с 192.168.0.15.
-D Удаление правила:
iptables -D INPUT 10
удалить правило в цепочке INPUT с номером 10.
-I Вставка правила в определенную часть списка:
iptables -I INPUT 5 -s 192.168.0.15 -j DROP
вставить правило 5-м по списку.
-R Замена правила.
iptables -R OUTPUT 5 -s 192.168.0.15 -j ACCEPT
заменить наше 5-е правило с запрещающего на разрешающее.
 
-F Сброс правил в цепочке.
iptables -F INPUT
-Z Обнуление статистики.
iptables -Z INPUT
-N Создание цепочки.
iptables -N CHAINNEW
-X Удаление цепочки.
iptables -X CHAINNEW
-P Определение правила по умолчанию.
iptables -P INPUT DROP
-E Переименовывание цепочки.
iptables -E CHAINNEW CHAINOLD

Условия

Данные ключи определяют условия правила.

Ключ Описание и примеры
-p Сетевой протокол. Допустимые варианты — TCP, UDP, ICMP или ALL.
iptables -A INPUT -p tcp -j ACCEPT
разрешить все входящие tcp-соединения.
-s Адрес источника — имя хоста, IP-адрес или подсеть в нотации CIDR.
iptables -A INPUT -s 192.168.0.50 -j DROP
запретить входящие с узла 192.168.0.50
-d Адрес назначения. Принцип использования аналогичен предыдущему ключу -s.
iptables -A OUTPUT -d 192.168.0.50 -j DROP
запретить исходящие на узел 192.168.0.50
-i Сетевой адаптер, через который приходят пакеты (INPUT).
iptables -A INPUT -i eth2 -j DROP
запретить входящие для Ethernet-интерфейса eth2.
-o Сетевой адаптер, с которого уходят пакеты (OUTPUT).
iptables -A OUTPUT -o eth3 -j ACCEPT
разрешить исходящие с Ethernet-интерфейса eth3.
—dport Порт назначения.
iptables -A INPUT -p tcp —dport 80 -j ACCEPT
разрешить входящие на порт 80.
—sport Порт источника.
iptables -A INPUT -p tcp —sport 1023 -j DROP
запретить входящие с порта 1023.

Перечисленные ключи также поддерживают конструкцию с использованием знака !. Он инвертирует условие, например,
iptables -A INPUT -s ! 192.168.0.50 -j DROP
запретит соединение всем хостам, кроме 192.168.0.50.

Действия

Действия, которые будут выполняться над пакетом, подходящим под критерии условия. Для каждой таблицы есть свой набор допустимых действий. Указываются с использованием ключа -j.

Таблица Действие Описание
filter ACCEPT Разрешает пакет.
DROP Запрещает пакет.
REJECT Запрещает с отправкой сообщения источнику.
nat MASQUERADE Для исходящих пакетов заменяет IP-адрес источника на адрес интерфейса, с которого уходит пакет.
SNAT Аналогично MASQUERADE, но с указанием конкретного сетевого интерфейса, чей адрес будет использоваться для подмены. 
DNAT Подмена адреса для входящих пакетов.
REDIRECT Перенаправляет запрос на другой порт той же самой системы.
mangle TOS Видоизменение поля TOS (приоритезация трафика).
DSCP Изменение DSCP (тоже приоритезация трафика).
TTL Изменение TTL (время жизни пакета).
HL Аналогично TTL, но для IPv6.
MARK Маркировка пакета. Используется для последующей фильтрации или шейпинга.
CONNMARK Маркировка соединения.
TCPMSS Изменение значения MTU.

Примеры часто используемых команд iptables

Общие команды

Просмотр правил с их номерами:

iptables -L —line-numbers

Для каждой таблицы смотреть правила нужно отдельно: 

iptables -t nat -L —line-numbers

Удалить все правила:

iptables -F

Установить правила по умолчанию:

iptables -P INPUT DROP

iptables -P OUTPUT DROP

* в данных примерах по умолчанию для всех входящих (INPUT) и исходящих (OUTPUT) пакетов будет работать запрещающее правило (DROP).

Разрешить все

Способ 1. С помощью добавления правила:

iptables -I INPUT 1 -j ACCEPT

iptables -I OUTPUT 1 -j ACCEPT

iptables -I FORWARD 1 -j ACCEPT

* данные три команды создадут правила, которые разрешают все входящие, исходящие и транзитные пакеты.

Способ 2. Чисткой правил:

iptables -F

iptables -S

* здесь мы сначала удаляем все правила (-F), затем устанавливаем политику по умолчанию — разрешать входящие, исходящие и транзитные (-S).

Способ 3. Отключение сервиса (удобно для диагностики проблем на время отключить firewall):

service iptables stop

iptables stop

Работа с правилами

1. Добавить правило в конец списка:

iptables -A INPUT -p tcp —dport 25 -j ACCEPT

iptables -A INPUT -p tcp -s ! 192.168.0.25 —dport 993 -i eth0 -j ACCEPT

2. Добавить диапазон портов:

iptables -A INPUT -p tcp —dport 3000:4000 -j ACCEPT

* в данном случае, от 3000 до 4000.

3. Вставить правило:

iptables -I FORWARD 15 -p udp -d 8.8.8.8 —dport 53 -i eth1 -j ACCEPT

4. Заблокировать определенный IP-адрес для подключения по 25 порту:

iptables -I INPUT 1 -s 1.1.1.1 -p tcp —dport 25 -j DROP

5. Разрешить несколько портов:

iptables -A INPUT -p tcp —match multiport —dports 20,21,25,80,8080,3000:4000 -j ACCEPT

Проброс портов (port forwarding)

Рассмотрим пример проброса одного порта и диапазона портов.

Один порт (одинаковые порты)

Существует два способа настройки.

1. Правила PREROUTING + POSTROUTING:

iptables -t nat -A PREROUTING -p tcp -m tcp -d 19.8.232.80 —dport 22 -j DNAT —to-destination 192.168.1.15:22

iptables -t nat -A POSTROUTING -p tcp -m tcp -s 192.168.1.15 —sport 22 -j SNAT —to-source 19.8.232.80:22

* где 19.8.232.80 — адрес, на котором слушаем запросы на подключение; 22 — порт для проброса; 192.168.1.15 — внутренний IP-адрес, на который переводим все запросы.

2. Правила PREROUTING + FORWARD:

iptables -t nat -A PREROUTING -p tcp -i eth1 —dport 22 -j DNAT —to-destination 192.168.1.15:22

iptables -A FORWARD -p tcp -d 192.168.1.15 —dport 22 -m state —state NEW,ESTABLISHED,RELATED -j ACCEPT

* где eth1 — сетевой интерфейс, на котором слушаем запросы; 22 — порт для проброса; 192.168.1.15 — внутренний IP-адрес, на который переводим все запросы.

Один порт (разные порты)

Рассмотрим ситуацию, когда мы слушаем один порт, а пробрасываем на другой.

iptables -t nat -A PREROUTING -p tcp -i eth1 —dport 8022 -j DNAT —to-destination 192.168.1.15:22

iptables -A FORWARD -p tcp -d 192.168.1.15 —dport 22 -m state —state NEW,ESTABLISHED,RELATED -j ACCEPT

* где eth1 — сетевой интерфейс, на котором слушаем запросы; 8022 — порт для проброса, на котором будем слушать запросы; 22 — порт для проброса на внутренний адрес; 192.168.1.15 — внутренний IP-адрес, на который переводим все запросы.

Диапазон портов

При необходимости пробросить диапазон портов, используем команды:

iptables -t nat -I PREROUTING -p tcp -m tcp —dport 1000:5000 -j DNAT —to-destination 192.168.1.15:1000-5000

iptables -A FORWARD -d 192.168.1.15 -i eth1 -p tcp -m tcp —dport 1000:5000 -j ACCEPT

* где eth1 — сетевой интерфейс, на котором слушаем запросы; 1000:5000 — порты для проброса (от 1000 до 5000); 192.168.1.15 — внутренний IP-адрес, на который переводим все запросы.

Стартовая настройка

Мы можем начать настройку брандмауэра на сервере с этих команд.

Разрешаем SSH:

iptables -A INPUT -p tcp —dport 22 -j ACCEPT

Создаем правила для нормальной работы apt или yum:

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

Разрешаем ICMP (для выполнения команды ping):

iptables -A INPUT -p icmp -j ACCEPT

Разрешаем все входящие на адрес локальной петли:

iptables -A INPUT -i lo -j ACCEPT

Ставим политику запрета на входящие и разрешаем все исходящие:

iptables -P INPUT DROP

iptables -P OUTPUT ACCEPT

Настройка по умолчанию

Если мы хотим вернуть настройки в первоночальное значение (разрешено все, правил нет), выполняем команды ниже.

Сначала ставим разрешающую политику для основных цепочек:

iptables -S

Ставим политику разрешения на входящие и исходящие:

iptables -P INPUT ACCEPT

iptables -P OUTPUT ACCEPT

Удаляем все правила во всех таблицах:

iptables -F

iptables -t nat -F

iptables -t mangle -F

Удаляем все цепочки, которые не используются:

iptables -X

Сохранение правил (permanent)

По умолчанию, все правила перестают работать после перезапуска сети или компьютера. Для сохранения правил после перезагрузки есть несколько способов настройки.

Способ 1. iptables-save (универсальный)

Сохраняем правила в файл:

iptables-save > /etc/iptables.rules

Чтобы восстановить правила, достаточно ввести команду:

iptables-restore < /etc/iptables.rules

А для автоматического восстановления правил при загрузке сервера или перезагрузки сети, создадим файл:

vi /etc/network/if-pre-up.d/iptables

#!/bin/bash
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

iptables-restore < /etc/iptables.rules
exit 0 

И делаем его исполняемым:

chmod +x /etc/network/if-pre-up.d/iptables 

В версиях постарше открываем настройки сети:

vi /etc/network/interfaces

и добавляем строку:

pre-up iptables-restore < /etc/iptables.rules

Способ 2. iptables-persistent (Debian/Ubuntu)

Ставим пакет iptables-persistent:

apt install iptables-persistent

Для сохранения правил вводим команду:

netfilter-persistent save

Способ 3. service iptables (CentOS)

Работает в старых версиях Linux и CentOS. Необходима установка пакета:

yum install iptables-services

apt install iptables-services

* первая команда для CentOS, вторая — для Ubuntu.

Сохраняем правила командой:

service iptables save

* правила будут сохранены в файл /etc/sysconfig/iptables.

Чтобы правила восстанавливались автоматически при старте компьютера, разрешаем автозапуск сервиса.

а) в более новых версиях Linux:

systemctl enable iptables

б) в версиях постарше:

chkconfig iptables on

update-rc.d iptables defaults

* первая команда для CentOS, вторая для Ubuntu.

Ubuntu и CentOS

В современных операционных системах Ubuntu и CentOS по умолчанию нет iptables. Необходимо его установить или пользоваться более новыми утилитами.

В CentOS

В качестве штатной программы управления брандмауэром используется firewall-cmd. Подробнее читайте инструкцию Как настроить firewalld в CentOS.

Если необходимо пользоваться iptables, устанавливаем пакет с утилитой:

yum install iptables-services

Отключаем firewalld:

systemctl stop firewalld

systemctl disable firewalld 

Разрешаем и запускаем iptables:

systemctl enable iptables

systemctl start iptables

В Ubuntu

Для управления брандмауэром теперь используется ufw.

Для работы с iptables, устанавливаем следующий пакет:

apt install iptables-persistent

Отключаем ufw:

ufw disable

Состояние перевода: На этой странице представлен перевод статьи 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. Пакет ulogd доступен в репозитории [community].

Смотрите также

  • Iptables в Википедии
  • Port knocking
  • Официальный сайт iptables
  • Руководство по iptables версии 1.2.2 от Oskar Andreasson
  • Debian Wiki — iptables
  • Безопасное использование Connection Tracking helpers

Каждый компьютер, подключенный к сети, находится в потенциальной опасности. В сети очень много угроз начиная от программ, которые будут пытаться любым способом проникнуть в систему и заканчивая хакерами, которые хотят получить доступ к нужному им компьютеру. А программное обеспечение, установленное на компьютере, может содержать еще не известные и неисправленные уязвимости, которые и могут стать дырой в безопасности.

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

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

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

Виды пакетов

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

Соответственно в фильтре iptables все пакеты делятся на три аналогичные цепочки:

  • Input — обрабатывает входящие пакеты и подключения. Например, если какой-либо внешний пользователь пытается подключиться к вашему компьютеру по ssh или любой веб-сайт отправит вам свой контент по запросу браузера. Все эти пакеты попадут в эту цепочку;
  • forward — эта цепочка применяется для проходящих соединений. Сюда попадают пакеты, которые отправлены на ваш компьютер, но не предназначены ему, они просто пересылаются по сети к своей цели. Как я уже говорил, такое наблюдается на маршрутизаторах или, например, если ваш компьютер раздает wifi;
  • output — эта цепочка используется для исходящих пакетов и соединений. Сюда попадают пакеты, которые были созданы при попытке выполнить ping losst.pro или когда вы запускаете браузер и пытаетесь открыть любой сайт.

Но если вы думаете что можно просто полностью закрыть цепочку Input для увеличения безопасности, то вы очень сильно ошибаетесь. При работе сети используются обе цепочки input и output. Например, вы пытаетесь выполнить ping, данные отправляются через output, но ответ приходит через input. То же самое происходит при просмотре сайтов и других действиях. А вот цепочка forward может вообще не использоваться если ваш компьютер не является маршрутизатором. Так что настройка iptables должна выполняться очень аккуратно.

Правила и действия

Перед тем как перейти к созданию списка правил iptables нужно рассмотреть как они работают и какие бывают. Для каждого типа пакетов можно установить набор правил, которые по очереди будут проверяться на соответствие с пакетом и если пакет соответствует, то применять к нему указанное в правиле действие. Правила образуют цепочку, поэтому input, output и forward называют цепочками, цепочками правил. Действий может быть несколько:

  • ACCEPT — разрешить прохождение пакета дальше по цепочке правил;
  • DROP — удалить пакет;
  • REJECT — отклонить пакет, отправителю будет отправлено сообщение, что пакет был отклонен;
  • LOG — сделать запись о пакете в лог файл;
  • QUEUE — отправить пакет пользовательскому приложению.

Правила могут проверять любые соответствия, например, по ip, по порту получателя или отправителя, заголовкам пакета и многому другому. Если пакет не подходит ни одному из правил, то к нему применяется действие по умолчанию, обычно ACCEPT.

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

  • prerouting — в эту цепочку пакет попадает перед обработкой iptables, система еще не знает куда он будет отправлен, в input, output или forward;
  • postrouting — сюда попадают все проходящие пакеты, которые уже прошли цепочку forward.

Но это еще не все. У нас еще есть таблицы iptables, с которыми тоже желательно разобраться.

Таблицы ipatables

Над цепочками правил в iptables есть еще один уровень абстракции, и это таблицы. В системе есть несколько таблиц, и все они имеют стандартный набор цепочек input, forward и output. Таблицы предназначены для выполнения разных действий над пакетами, например для модификации или фильтрации. Сейчас это для вас не так важно и будет достаточно знать что фильтрация пакетов iptables осуществляется в таблице filter. Но мы рассмотрим их все:

  • raw — предназначена для работы с сырыми пакетами, пока они еще не прошли обработку;
  • mangle — предназначена для модификации пакетов;
  • nat — обеспечивает работу nat, если вы хотите использовать компьютер в качестве маршрутизатора;
  • filter — основная таблица для фильтрации пакетов, используется по умолчанию.

С теорией почти все, теперь давайте рассмотрим утилиту командной строки iptables, с помощью которой и выполняется управление системой iptables.

Утилита Iptables

Подсистема iptables и netfilter встроены в ядро, но вот набор утилит для управления всем этим не всегда поставляется вместе с системой. Для установки утилиты в Ubuntu наберите:

sudo apt install iptables

А в дистрибутивах, основанных на Fedora, установка iptables выполняется немного по-другому:

sudo yum install iptables

Когда установка iptables будет завершена, можно переходить к настройке, но давайте сначала рассмотрим синтаксис утилиты. Обычно команда имеет такой общий вид:

$ iptables -t таблица действие цепочка дополнительные_параметры

Теперь давайте рассмотрим параметры iptables, таблица указывает таблицу, с которой нужно работать, этот параметр можно упустить, действие — нужное действие, например, создать или удалить правило, а дополнительные параметры описывают действие и правило, которое нужно выполнить.

Осталось рассмотреть основные действия, которые позволяет выполнить iptables:

  • -A — добавить правило в цепочку;
  • — проверить все правила;
  • -D — удалить правило;
  • -I — вставить правило с нужным номером;
  • -L — вывести все правила в текущей цепочке;
  • -S — вывести все правила;
  • -F — очистить все правила;
  • -N — создать цепочку;
  • -X — удалить цепочку;
  • -P — установить действие по умолчанию.

Дополнительные опции для правил:

  • -p — указать протокол, один из tcp, udp, udplite, icmp, icmpv6,esp, ah, sctp,
    mh;
  • -s — указать ip адрес устройства-отправителя пакета;
  • -d — указать ip адрес получателя;
  • -i — входной сетевой интерфейс;
  • -o — исходящий сетевой интерфейс;
  • -j — выбрать действие, если правило подошло.

Теперь вы можем перейти рассмотрению примеров того как выполняется настройка iptables.

Примеры настройки Iptables

Мы рассмотрим несколько основных примеров, чтобы вы смогли закрепить все прочитанное выше.

Список правил

Сначала давайте рассмотрим как выполняется просмотр правил iptables, для этого достаточно опции -L:

iptables -L

iptables

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

iptables -L INPUT

Очистка правил

Вы не можете просто так отключить iptables остановив сервис обновления правил iptables через systemd или даже удалив набор утилит для настройки. Подсистема работает на уровне ядра и не зависит от того, что там у вас установлено. Поэтому если сделаете что-то не так, то нужно будет очистить правила. Для этого выполните:

sudo iptables -F

Или только для определенной цепочки:

sudo iptables -F Input

Напоминаю, что все эти действия выполняются для таблицы по умолчанию — filter.

Правила по умолчанию

Как я уже говорил, если для пакета не подходит ни одно правило, то для него применяется действие по умолчанию. Его можно задать с помощью опции -p:

sudo iptables -p INPUT ACCEPT
$ sudo iptables -p OUTPUT ACCEPT
$ sudo iptables -p FORWARD DROP

В этом примере мы разрешаем цепочки INPUT и OUTPUT, но запрещаем FORWARD.

sudo iptables -L

iptables1

Блокировка пакетов

Для блокировки пакетов мы можем использовать действие DROP, фильтровать пакеты, которые нужно заблокировать мы можем по множеству критериев, например, протоколу, ip адресу, маске сети, порту и многому другому.

Вот так будет выглядеть команда, которая позволяет добавить правило iptables для блокировки всех входящих пакетов от 10.10.10.10:

sudo iptables -A INPUT -s 10.10.10.10 -j DROP

А теперь исходящие пакеты на этот же адрес:

sudo iptables -A OUTPUT -s 10.10.10.10 -j DROP

iptables2

Блокировка диапазона ip выполняется подобным образом. Для этого нужно использовать маску сети 10.10.10.0/24. Это будут все адреса начиная от 10.10.10.0 до 10.10.10.255:

sudo iptables -A INPUT -s 10.10.10.0/24 -j DROP

Или расширенный вариант маски:

sudo iptables -A INPUT -s 10.10.10.0/255.255.255.0 -j DROP

Также вы можете заблокировать все входящие соединения ssh:

sudo iptables -A INPUT -p tcp --dport ssh -s 10.10.10.10 -j DROP

Как видите, добавить правило iptables очень просто.

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

Удаление правил iptables выполняется точно так же, как и создание новых, только вместо опции A нужно использовать опцию D. Сначала смотрим список правил:

sudo iptables -L

iptables3

Например, вот так можно удалить правило iptables, которое было создано вторым:

sudo iptables -D OUTPUT -s 10.10.10.10 -j DROP

iptables5

Также вы можете полностью очистить iptables выполнив команду с опцией -F:

sudo iptables -F

iptables6

Сохранить правила Iptables

Все настройки iptables, которые вы указали с помощью этих команд сохранятся только до перезагрузки. После перезагрузки компьютера все изменения будут стерты. Поэтому чтобы сохранить правила iptables, нужно выполнить специальную команду. Только в разных дистрибутивах она отличается. В Ubuntu выполните:

sudo /sbin/iptables-save

А в Red Hat или CentOS:

sudo /sbin/service iptables save

Выводы

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

На завершение видео о том, как увеличить безопасность вашего сервера:

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Подключение к сети само по себе несет в себе «угрозу», ведь за счет «видимости» хакеры получают возможность просканировать удаленный компьютер на предмет открытых портов, доступных для подключения извне. И наиболее подвержены сетевым опасностям серверы, которые специально и «открывают» для внешних пользователей.

Что такое Iptables?

Операционные системы Linux, на которых чаще всего и функционируют серверы (виртуальные машины), имеют встроенный инструмент защиты – программный фильтр Iptables. Все сетевые пакеты идут через ядро приложения и проходят проверку на безопасность для компьютера. Сценария всего два – или данные передаются дальше на обработку, или полностью блокируются.

Виды пакетов

Информационные пакеты фильтруются исходя из назначения. Под контроль попадают все данные, входящие на сервер, исходящие из него или проходящие через него как маршрутизатор (например, если компьютер используется в качестве прокси). Такой подход создает сплошной защитный экран (файрвол), через который практически нереально проникнуть с вредоносными целями.

Iptables

Описания пакетов:

  1. Input. Обрабатываются входящие подключения вроде подключения по протоколу SSH или при отправке на веб-сайт каких-либо файлов.
  2. Forward. Цепочка формируется при активации проходящего соединения, когда информация предназначена «третьему» компьютеру, а текущий сервер выполняет роль маршрутизатора.
  3. Output. Исходящие пакеты данных, например, при запуске какого-либо сайта в браузере или при проверке скорости соединения и доступности PING.

В реальной работе сервера постоянно формируется минимум два вида пакетов – Input и Output. Ведь на каждый запрос пользователя положено дать ответ: сначала о поступлении данных на сервер, а затем и о результате обработки. Если «принято решение» отказать в доступе, об этом также сообщается на удаленное рабочее место. Иначе запрос зависнет, и пользователь будет видеть пустой экран.

Правила и действия Iptables

На каждый тип пакетов распространяется определенный набор правил, и их следует учитывать при настройке программы Iptables. Большая часть запросов проходит в виде последовательных цепочек в различных комбинациях. Если ошибиться на этом этапе, приложение будет функционировать со сбоями и блокировать «полезные» запросы.

Правила и действия Iptables

Примеры действий:

  1. ACCEPT – пропустить пакет данных далее по цепочке;
  2. DROP – полностью удалить пакет;
  3. REJECT – отклонить запрос и направить пользователю ответ с информацией об этом;
  4. LOG – инициируется запись в лог-файл об обработанном пакете;
  5. QUEUE – отправка данных на компьютер пользователя.

Правила проверки устанавливаются в зависимости от характера соединения. Возможен мониторинг IP-адреса, порта подключения, отправителя, заголовка. Если пакет не проходит хотя бы по одному критерию, осуществляется действие ACCEPT (сквозное пропускание пакета, который не требуется блокировать файрволом). Фильтрация возможна на двух этапах:

  • prerouting – система только получила пакет, и нет команды «что с ним делать»: обрабатывать на сервере, возвращать пользователю или пропускать насквозь;
  • postroutnig – обработка после оценки «пункта назначения».

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Подписаться

Таблицы Iptables

Существует еще один «уровень» обработки – это таблицы, содержащие правила обработки тех или иных действий над пакетами. Например, фильтрация данных в Iptables осуществляется в таблице filter. К ней придется обращаться чаще всего.

Варианты:

  • raw – предназначен для работы с «сырыми» данными, еще не прошедшими обработку;
  • mangle – используется для модификации пакетов;
  • nat – обеспечивает работу сервера в качестве маршрутизатора;
  • filter – основная таблица, используемая «по умолчанию».

Об основах работы с утилитой Iptables я рассказал, теперь можно приступать к тестовому запуску.

Запуск утилиты Iptables

Перед активацией приложение требуется установить из стандартного репозитория Linux. Так, для инсталляции в Ubuntu подойдет команда:

$ sudo apt install iptables

В дистрибутиве, базируемом на ядре Fedora, она выглядит несколько иначе:

$ sudo yum install iptables

Общий синтаксис запуска программы выглядит следующим образом:

$ iptables -t таблица действие цепочка дополнительные_параметры

Запуск iptables

Перечень основных действий, для выполнения которых используется Iptables:

  1. -A – добавить правило в цепочку;
  2. -C – проверить применяемые правила;
  3. -D – удалить текущее правило;
  4. -I – вставить правило с указанным номером;
  5. -L – вывести правила текущей цепочки;
  6. -S – вывести все активные правила;
  7. -F – очистить все правила;
  8. -N – создать цепочку;
  9. -X – удалить цепочку;
  10. -P – установить действие «по умолчанию».

В качестве дополнительных параметров используются опции:

  1. -p – вручную установить протокол (TCP, UDP, UDPLITE, ICMP, ICMPv6, ESP, AH, SCTP, MH);
  2. -s – указать статичный IP-адрес оборудования, откуда отправляется пакет данных;
  3. -d – установить IP получателя;
  4. -i – настроить входной сетевой интерфейс;
  5. -o – то же самое в отношении исходящего интерфейса;
  6. -j – выбрать действие при подтверждении правила.

Примеры настройки Iptables

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

Список правил

Просмотр правил Iptables осуществляется командой:

$ iptables –L

Также есть возможность указать нужную цепочку, например:

$ iptables -L INPUT

Очистка правил

При любых ошибках в работе Iptables, чтобы исключить нарушение функционирования ядра перед другими действиями, требуется очистить правила, «обнулить» вводные данные. Выполняется эта процедура командой:

$ sudo iptables –F

Если речь идет об определенной цепочке, то она будет выглядеть иначе:

$ sudo iptables -F Input

Перечисленные действия выполняются для таблицы filter, которая подключена изначально.

Правила «по умолчанию»

Задаются правила «по умолчанию» вручную. Пример команд:

$ sudo iptables -p INPUT ACCEPT

$ sudo iptables -p OUTPUT ACCEPT

$ sudo iptables -p FORWARD DROP

Здесь мы разрешаем все цепочки INPUT и OUTPUT, запрещаем FORWARD.

Блокировка пакетов

Заблокировать пакеты можно действием DROP. Оно позволяет включать фильтрацию по разным признакам вроде IP-адреса, маске сети, порту и пр.

Пример:

$ sudo iptables -A INPUT -s 20.20.20.20 -j DROP

Блокируются входящие пакеты на IP 20.20.20.20.

$ sudo iptables -A OUTPUT -s 20.20.20.20 -j DROP

Теперь мы заблокировали пакеты, исходящие на IP 20.20.20.20.

Есть возможность указать маску сети, например, 20.20.20.0/255. Тогда правила будут применяться ко всем IP, входящим в указанный диапазон. Если же требуется заблокировать подключение строго по определенному протоколу, вводится команда:

$ sudo iptables -A INPUT -p tcp --dport ssh -s 10.10.10.10 -j DROP

Она блокирует все входящие соединения по SSH.

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

При удалении правил в Iptables вводится команда с опцией -D. Но перед этим может понадобиться просмотреть перечень правил:

$ sudo iptables -L

Настройка iptablesПример удаления правила:

$ sudo iptables -A OUTPUT -s 10.10.10.10 -j DROP

Если требуется полное удаление правил, применяется команда:

$ sudo iptables –F

Сохранение правила Iptables

Теперь остается опробовать режим сохранения правил. Важно учитывать, что он действует до перезагрузки компьютера. После этой процедуры необходимо задавать их заново. В Ubuntu процесс требует ввода команды:

$ sudo /sbin/iptables-save

Для операционных систем на ядре Red Hat и CentOS она выглядит иначе:

$ sudo /sbin/service iptables save

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

VDS Timeweb арендовать

Для новичков и продвинутых пользователей операционный системы Линукс был разработан специальный межсетевой экран (так называемый «файрвол») для защиты от угроз извне, который носит имя Iptables. Ниже в инструкции мы объясним, как его установить и настроить на любых машинах под ОС Linux.

Что представляет собой Iptables

Данная утилита – это надежный межсетевой экран, минимизирующий риск вирусных и хакерских атак. Процесс настройки файрвола происходит через командную строку при помощи установленных команд, которые позволяют юзеру самостоятельно контролировать поступление и отправление трафика. При попытке установки соединений с ПК, утилита обращается к своим правилам и проверяет, пропустить или ограничить соединение. В случае, когда никакого конкретного правила не выставлено, действия проходят по умолчанию.

Файрвол предусмотрен стандартно во всех операционных системах Линукс. Для установки, если его внезапно не оказалось в сборке, или обновления следует применить такую команду:

sudo apt-get install iptables

Альтернативой данной утилите может послужить Firestarter – он имеет графический интерфейс и разработан специально для пользователей, которые испытывают трудности с работой через командную строку.

В случае настроек Iptables по удаленному SSH-соединению, пользователю следует проявлять аккуратность: одно ошибочное правило способно прервать подключение и запретить юзеру доступ к удаленной машине.

Какие бывают правила

Для легкой работы с файрволом разработана тройка основных правил (команд):

1.Input.

Правило применяется, когда необходимо контролировать входящий трафик. Например, когда юзер подключается к удаленному серверу по протоколу Secure Shell, файрвол начнет сравнивать его айпи с другими айпи из своего списка. В зависимости от результата, то есть от наличия в списке запретов, доступ пользователю будет открыт или закрыт.

2.Forward.

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

3.Output.

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

Примечание:

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

Как определиться с назначением файрвола

Перед тем, как заниматься настройкой утилиты, потребуется разобраться с ее предназначением, а именно – действующими цепочками правил, то есть то, что она будет делать по умолчанию. Как отреагировать, когда запрашиваемые соединения не подходят ни к одному правилу?

Для начала потребуется понять, какие из настроек межсетевого экрана уже установлены. Для этого применяется команда –L:

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

Скриншот №1. Настройки межсетевого экрана

Для четкого и понятного вывода информации можно воспользоваться дополнительной командой «grep». В итоге мы получаем тройку цепочек, у каждой из которых стоит разрешение приема трафика. Подобные правила предпочитают устанавливать при стандартной настройке.

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

iptables --policy INPUT ACCEPT iptables --policy OUTPUT ACCEPT iptables --policy FORWARD ACCEPT

Правильнее будет заблаговременно разрешить все входящие/исходящие подключения, после чего выставлять запреты под конкретный порт и айпи-адрес.

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

iptables --policy INPUT DROP iptables --policy OUTPUT DROP iptables --policy FORWARD DROP

Что делать с соединением

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

Accept – разрешение определенного соединения;

Drop – игнорирование запросов (межсетевой экран продолжает свое функционирование, будто никакого запроса не происходило, а запрашивающие ресурсы не узнают об игнорировании);

Reject – блокировка входящего трафика и отправка ответных сообщений с обозначением ошибки (в таком случае запрашивающие ресурсы будут уведомлены о блокировке их трафика).

Пример того, как будет выглядеть ping для

Разрешенного соединения (Accept):

Ping для разрешенного соединения

Скриншот №2. Ping для разрешенного соединения

Проигнорированного трафика (Drop):

Ping для проигнорированного трафика

Скриншот №3. Ping для проигнорированного трафика

Отклоненного подключения (Reject):

Ping для отклоненного подключения

Скриншот №4. Ping для отклоненного подключения

Разрешение и блокировка указанных соединений Iptables

Как только политика отношения к трафику настроена, пора приступать к определению правил для конкретных соединений. Мы рассмотрим вариант с отклонением указанного подключения. Способы для разрешения и игнорирования будут устанавливаться похожим методом.

Воспользуемся командой –А. Она позволит добавить новое правило к уже имеющейся цепочке. Межсетевой экран начинает проверку с самого верха, проходя по каждому из правил до тех пор, пока не обнаружит совпадения или не закончит список.

В случае, когда необходимо разместить правила в определенное место (перед каким-то определенным), следует воспользоваться командой:

iptables -I [цепочка] [номер позиции по списку для нового правила]

Что делать с соединениями от одного айпи

Для блокировки трафика, поступающего из одного и того же источника (например, айпи 120.120.120.120) подойдет команда:

iptables -A INPUT -s 120.120.120.120 -j DROP

Для блокировки трафика, поступающего с нескольких айпишников в определенном диапазоне, следует воспользоваться стандартной записью масок посредством слэша:

iptables -A INPUT -s 120.120.120.0/24 -j DROP

Либо записью необходимого диапазона:

iptables -A INPUT -s 120.120.120.0/255.255.255.0 -j DROP

Подключения к определенному порту

Следующая команда сделает блокировку соединений типа Secure Shell с хостом 120.120.120.120:

iptables -A INPUT -p tcp --dport ssh -s 120.120.120.120 -j DROP

На месте Secure Shell допустимо применение любого протокола. После команды –р указывается тип подключений, в данном случае – TCP. В случае, когда используется другой тип, следует указывать его.

Любому айпишнику будет запрещено подключаться к машине по Secure Shell соединению, если выполнить:

iptables -A INPUT -p tcp --dport ssh -j DROP

О состояниях соединения

Существует множество протоколов, которым требуется двусторонняя коммуникация. К примеру, пользователю понадобилось поработать с SSH-соединением, ему придется внести правило сразу и в Output, и в Input.

Что делать, если юзер хочет предоставить разрешение исключительно входящему соединению? В этом случае поможет состояние соединения. Оно даст возможность пользователю описать любую двустороннюю коммуникацию, в которой разрешено подключение заданного направления.

Разрешим соединение типа SSH, приходящее через хост 120.120.120.120. Система будет отправлять данные по этому протоколу только, если сессия установлена.

iptables -A INPUT -p tcp --dport ssh -s 120.120.120.120 -m state --state NEW,ESTABLISHED -j ACCEPT iptables -A OUTPUT -p tcp --sport 22 -d 120.120.120.120 -m state --state ESTABLISHED -j ACCEPT

Как сохранить изменения в конфигурации файрвола

После всех изменений, которые мы внесли в цепочку межсетевого экрана, понадобится их сохранение. Иначе перезапуск утилиты удалит проделанные нами настройки. Команда сохранения будет различаться от дистрибутива к дистрибутиву Линукс.

Для Убунту команда выглядит так:

=sudo /sbin/iptables-save

Для Red Hat и CentOS:

=/sbin/service iptables save

Либо

=/etc/init.d/iptables save

Дополнительно

Чтобы вывести сконфигурированное ранее правило:

iptables –L

Чтобы просмотреть данные о входящих/исходящих пакетах и трафике, достаточно добавить ключ –v.

Данные об имени хоста, протоколах, сетях появятся в цифровом виде, если дописать в команду –n.

Разом удалить все имеющиеся установленные правила возможно командой:

iptables –F

191028
Санкт-Петербург
Литейный пр., д. 26, Лит. А

+7 (812) 403-06-99

700
300

ООО «ИТГЛОБАЛКОМ ЛАБС»

191028
Санкт-Петербург
Литейный пр., д. 26, Лит. А

+7 (812) 403-06-99

700
300

ООО «ИТГЛОБАЛКОМ ЛАБС»

Понравилась статья? Поделить с друзьями:

А вот и еще наши интересные статьи:

  • Кредо дат руководство пользователя
  • Фамотидин инструкция по применению таблетки взрослым 40мг от чего помогает
  • Lens тинкер руководство
  • Инструкция фастум гель для наружного применения
  • Свечи индометациновые цена инструкция по применению при простатите

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии