PDA

Просмотр полной версии : iptables


BFenix
17.08.2009, 22:10
Начал настраивать фаервол для защиты сервера. Апач забивают банальным флудом на 80 порт. Ботнет небольшой (до 1к машин), ну по крайней мере мне так сказал атакующий(оказался норм штрих, просто делает то за что ему платят деньги).

Вот мой фаервол:


#!/bin/sh
EXT_DEV="eth2"
EXT_DEV_IP="ххх.ххх.ххх.ххх"

INT_DEV1="eth0"
INT_DEV1_IP="192.168.1.2"

INT_DEV2="eth1"
INT_DEV2_IP="192.168.2.2"

LO_DEV="lo"
LO_DEV_IP="127.0.0.1"

IPTABLES="/sbin/iptables"
## Needed to initially load modules
/sbin/depmod -a

# Required modules
/sbin/modprobe xt_connlimit
/sbin/modprobe ip_conntrack_ftp
/sbin/modprobe ip_conntrack_irc
/sbin/modprobe ip_conntrack_amanda
/sbin/modprobe ip_nat_ftp
/sbin/modprobe ip_nat_irc
/sbin/modprobe iptable_mangle
/sbin/modprobe iptable_nat
/sbin/modprobe ipt_LOG
/sbin/modprobe ipt_limit
/sbin/modprobe ipt_owner
/sbin/modprobe ipt_MASQUERADE
/sbin/modprobe ipt_geoip

# Required proc configuration
echo "30" > /proc/sys/net/ipv4/tcp_fin_timeout
echo "3600" > /proc/sys/net/ipv4/tcp_keepalive_time
echo "1" > /proc/sys/net/ipv4/ip_forward
echo "1" > /proc/sys/net/ipv4/conf/all/rp_filter
echo "1" > /proc/sys/net/ipv4/tcp_syncookies
echo "1" > /proc/sys/net/ipv4/tcp_syn_retries
echo "1" > /proc/sys/net/ipv4/tcp_keepalive_probes
echo "2" > /proc/sys/net/ipv4/tcp_synack_retries

# 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

# reset the default policies in the mangle table.
$IPTABLES -t mangle -P PREROUTING ACCEPT
$IPTABLES -t mangle -P INPUT ACCEPT
$IPTABLES -t mangle -P OUTPUT ACCEPT
$IPTABLES -t mangle -P FORWARD ACCEPT
$IPTABLES -t mangle -P POSTROUTING 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

# Set policies
$IPTABLES -P INPUT DROP
$IPTABLES -P OUTPUT ACCEPT
$IPTABLES -P FORWARD DROP

# Create userspecified chains
$IPTABLES -N bad_tcp_packets
$IPTABLES -N allowed
$IPTABLES -N tcp_packets
$IPTABLES -N udp_packets
$IPTABLES -N icmp_packets
$IPTABLES -N bogons
$IPTABLES -N black_country
$IPTABLES -N ddos

#is open for test
$IPTABLES -A INPUT -p TCP -s 0/0 --dport 22222 -j ACCEPT

#bogons chain
for host in `cat /etc/sysconfig/ip.deny.bogons`; do
$IPTABLES -A bogons -s $host -j DROP
done

#black.country chain
$IPTABLES -A black_country -m geoip --src-cc UA,RU,PL,BY,MD,NO,NL,LV,US,CA,DE,KZ,EE,GE,LT -j ACCEPT
$IPTABLES -A black_country -m geoip --src-cc IL,IT,UZ,GB,ES,FR,AZ,CZ,CH,SE,RO,FI,AM,TR,AU -j ACCEPT
$IPTABLES -A black_country -j DROP

# 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 DROP
$IPTABLES -A bad_tcp_packets -p tcp -m state --state INVALID -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 80 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 8080 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 53 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 443 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 21 -j allowed
$IPTABLES -A tcp_packets -p TCP -s 0/0 --dport 22222 -j allowed

# UDP chain
$IPTABLES -A udp_packets -p UDP -s 0/0 --destination-port 53 -j ACCEPT

# ICMP chain
$IPTABLES -A icmp_packets -p ICMP -d $EXT_DEV_IP --icmp-type echo-request -m limit --limit 5/s -j ACCEPT
$IPTABLES -A icmp_packets -p ICMP -s $EXT_DEV_IP -d 0/0 --icmp-type 0 -j ACCEPT
$IPTABLES -A icmp_packets -p ICMP -s $EXT_DEV_IP -d 0/0 --icmp-type 8 -j ACCEPT

# ddos chain
$IPTABLES -A ddos --dport 80 -m hashlimit --hashlimit 15/min --hashlimit-burst 30 --hashlimit-mode srcip --hashlimit-name DDOS --hashlimit-htable-size 32768 --hashlimit-htable-max 32768 --hashlimit-htable-gcinterval 1000 --hashlimit-htable-expire 100000 -j ACCEPT
$IPTABLES -A ddos -m connlimit --connlimit-above 15 -j DROP
$IPTABLES -A ddos -j ACCEPT


#input
$IPTABLES -A INPUT -p ALL -i $EXT_DEV -m state --state NEW,RELATED -j bogons
$IPTABLES -A INPUT -p ALL -i $EXT_DEV -m state --state NEW,RELATED -j black_country
$IPTABLES -A INPUT -p ALL -i $EXT_DEV -j ddos
$IPTABLES -A INPUT -p tcp -i $EXT_DEV -j bad_tcp_packets
$IPTABLES -A INPUT -p TCP -i $EXT_DEV -j tcp_packets
$IPTABLES -A INPUT -p UDP -i $EXT_DEV -j udp_packets
$IPTABLES -A INPUT -p ICMP -i $EXT_DEV -j icmp_packets

$IPTABLES -A INPUT -p ALL -i $INT_DEV1 -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $INT_DEV2 -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $LO_DEV -j ACCEPT

#output
$IPTABLES -A OUTPUT -p tcp -j bad_tcp_packets

# Bad TCP packets we don't want.
#list banned IP in file ip.denny
for host in `cat /etc/sysconfig/ip.deny`; do
$IPTABLES -A INPUT -s $host -i $EXT_DEV -j DROP
$IPTABLES -A FORWARD -s $host -i $EXT_DEV -j DROP
done

/sbin/iptables-save > /etc/sysconfig/iptables



Апач ложится через 10 секунд после начала атаки.

Если есть предложения по оптимизации, то готов выслушать.

PandoraBox
17.08.2009, 22:32
nginx в руки и вперед по настройкам Игоря Сысоева

ReduKToR
18.08.2009, 11:12
почитай тут (http://www.opennet.ru/docs/RUS/iptables/)

и тут (http://www.iptables.ru/) и вот тут (http://pm4u.narod.ru/iptables.htm)

BFenix
18.08.2009, 12:22
решил немного изменить вид цепочек. Пока внешний вид такой:
#!/bin/sh
EXT_DEV="eth2"
EXT_DEV_IP="ххх.ххх.ххх.ххх"

INT_DEV1="eth0"
INT_DEV1_IP="192.168.1.2"

INT_DEV2="eth1"
INT_DEV2_IP="192.168.2.2"

LO_DEV="lo"
LO_DEV_IP="127.0.0.1"

IPTABLES="/sbin/iptables"
## Needed to initially load modules
/sbin/depmod -a

# Required modules
/sbin/modprobe xt_connlimit
/sbin/modprobe ip_conntrack_ftp
/sbin/modprobe ip_conntrack_irc
/sbin/modprobe ip_conntrack_amanda
/sbin/modprobe ip_nat_ftp
/sbin/modprobe ip_nat_irc
/sbin/modprobe iptable_mangle
/sbin/modprobe iptable_nat
/sbin/modprobe ipt_LOG
/sbin/modprobe ipt_limit
/sbin/modprobe ipt_owner
/sbin/modprobe ipt_MASQUERADE
/sbin/modprobe ipt_geoip

# Required proc configuration
echo "30" > /proc/sys/net/ipv4/tcp_fin_timeout
echo "3600" > /proc/sys/net/ipv4/tcp_keepalive_time
echo "1" > /proc/sys/net/ipv4/ip_forward
echo "1" > /proc/sys/net/ipv4/conf/all/rp_filter
echo "1" > /proc/sys/net/ipv4/tcp_syncookies
echo "1" > /proc/sys/net/ipv4/tcp_syn_retries
echo "1" > /proc/sys/net/ipv4/tcp_keepalive_probes
echo "2" > /proc/sys/net/ipv4/tcp_synack_retries

# 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

# reset the default policies in the mangle table.
$IPTABLES -t mangle -P PREROUTING ACCEPT
$IPTABLES -t mangle -P INPUT ACCEPT
$IPTABLES -t mangle -P OUTPUT ACCEPT
$IPTABLES -t mangle -P FORWARD ACCEPT
$IPTABLES -t mangle -P POSTROUTING 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

# Set policies
$IPTABLES -P INPUT DROP
$IPTABLES -P OUTPUT ACCEPT
$IPTABLES -P FORWARD DROP

#is open for test
$IPTABLES -A INPUT -p TCP -s 0/0 --dport 22222 -j ACCEPT

#bogons chain
$IPTABLES -N bogons
for host in `cat /etc/sysconfig/ip.deny.bogons`; do
$IPTABLES -A bogons -s $host -j DROP
done

#list banned IP in file ip.deny
$IPTABLES -N black_ip
for host in `cat /etc/sysconfig/ip.deny`; do
$IPTABLES -A black_ip -s $host -i $EXT_DEV -j DROP
done

# ICMP chain
$IPTABLES -N icmp_ddos
$IPTABLES -A icmp_ddos -p ICMP -m hashlimit --hashlimit-name icmp0 --hashlimit 2/s --hashlimit-mode srcip --icmp-type 0 -j ACCEPT
$IPTABLES -A icmp_ddos -p ICMP -m hashlimit --hashlimit-name icmp8 --hashlimit 2/s --hashlimit-mode srcip --icmp-type 8 -j ACCEPT
$IPTABLES -A icmp_ddos -p ICMP -m hashlimit --hashlimit-name icmp11 --hashlimit 2/s --hashlimit-mode srcip --icmp-type 11 -j ACCEPT
$IPTABLES -A icmp_ddos -j DROP

# udp_ddos chain
$IPTABLES -N udp_ddos
$IPTABLES -A udp_ddos -p UDP -m hashlimit --hashlimit 15/min --hashlimit-burst 30 --hashlimit-mode srcip --hashlimit-name udp_ddos -j ACCEPT
$IPTABLES -A udp_ddos -p UDP -m connlimit --connlimit-above 15 -j DROP
$IPTABLES -A udp_ddos -p UDP -j DROP

# http_ddos chain
$IPTABLES -N http_ddos
$IPTABLES -A http_ddos -p TCP -m hashlimit --hashlimit 15/min --hashlimit-burst 30 --hashlimit-mode srcip --hashlimit-name httpddos --hashlimit-htable-size 32768 --hashlimit-htable-max 32768 --hashlimit-htable-gcinterval 1000 --hashlimit-htable-expire 100000 -j ACCEPT
$IPTABLES -A http_ddos -p TCP -m connlimit --connlimit-above 15 -j DROP
$IPTABLES -A http_ddos -p TCP -j DROP

# tcp_ddos chain
$IPTABLES -N tcp_ddos
$IPTABLES -A tcp_ddos -p TCP -m hashlimit --hashlimit 15/min --hashlimit-burst 30 --hashlimit-mode srcip --hashlimit-name tcpddos --hashlimit-htable-size 32768 --hashlimit-htable-max 32768 --hashlimit-htable-gcinterval 1000 --hashlimit-htable-expire 100000 -j ACCEPT
$IPTABLES -A tcp_ddos -p TCP -m connlimit --connlimit-above 15 -j DROP
$IPTABLES -A tcp_ddos -p TCP -j DROP

# syn_flood chain
$IPTABLES -N syn_flood
$IPTABLES -A syn_flood -m hashlimit --hashlimit 1/s --hashlimit-burst 4 --hashlimit-mode srcip --hashlimit-name syn_flood -j ACCEPT

# bad_tcp_packets chain
$IPTABLES -N 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
$IPTABLES -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j DROP
$IPTABLES -A bad_tcp_packets -p tcp -m state --state INVALID -j DROP

#protocol_filter chain
$IPTABLES -N protocol_filter
$IPTABLES -A protocol_filter -p tcp -j bad_tcp_packets
$IPTABLES -A protocol_filter -p tcp -j syn_flood
$IPTABLES -A protocol_filter -p tcp -m multiport --dport 53,21,22222 -j tcp_ddos
$IPTABLES -A protocol_filter -p tcp -m multiport --dport 80,8080,443 -j http_ddos
$IPTABLES -A protocol_filter -p UDP --dport 53 -j udp_ddos
$IPTABLES -A protocol_filter -p ICMP -j icmp_ddos
$IPTABLES -A protocol_filter -j DROP

#black.country chain
$IPTABLES -N black_country
$IPTABLES -A black_country -m geoip --src-cc UA,RU,PL,BY,MD,NO,NL,LV,US,CA,DE,KZ,EE,GE,LT -j protocol_filter
$IPTABLES -A black_country -m geoip --src-cc IL,IT,UZ,GB,ES,FR,AZ,CZ,CH,SE,RO,FI,AM,TR,AU -j protocol_filter
$IPTABLES -A black_country -j DROP

#input
$IPTABLES -A INPUT -p ALL -i $INT_DEV1 -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $INT_DEV2 -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $LO_DEV -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $EXT_DEV -j black_ip
$IPTABLES -A INPUT -p ALL -i $EXT_DEV -m state --state NEW,RELATED -j bogons
$IPTABLES -A INPUT -p ALL -i $EXT_DEV -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPTABLES -A INPUT -p ALL -i $EXT_DEV -m state --state NEW,RELATED -j black_country

/sbin/iptables-save > /etc/sysconfig/iptables
echo "Firewall started"[

BFenix
19.08.2009, 12:23
Этот фаервол + enginx вчера в тесте выдержали небольшой ддос с 70 машин.

На сайте даже небыло никаких признаков нагрузки.

Скиньте плиз ссылки на инфу по оптимизации апача.

ReduKToR
19.08.2009, 13:57
почитай тут (http://www.opennet.ru/base/dev/web_tune.txt.html)
тут (http://ru.b2evo.net/demo/blogs/blog2.php/2009/05/12/apache)
еще вот тут (http://www.opennet.ru/tips/sml/83.shtml) и тут (http://www.opennet.ru/base/dev/web_tune.txt.html)

ReduKToR
19.08.2009, 13:58
Этот фаервол + enginx вчера в тесте выдержали небольшой ддос с 70 машин.
это очень мало..... восновном с таким кол-вом ботов никто даже соваться небудет.....

BFenix
19.08.2009, 15:26
это очень мало..... восновном с таким кол-вом ботов никто даже соваться небудет.....


Я знаю, но раньше я и от этого числа ложился.

З.Ы. Сенк за ссылки.

З.З.Ы. кто-то из вас сможет меня потестить норм ботом?

ReduKToR
19.08.2009, 15:56
З.З.Ы. кто-то из вас сможет меня потестить норм ботом?

небоишся что хостер выгонит? ну а по делу: стучи вечером, буду дома помогу....потестимс

ReduKToR
23.08.2009, 17:10
iptables + geoip: фильтруем трафик по странам
На www.netfilter.org просто куча всяких патчей и приблуд на ядро/iptables, на все случаи жизни есть. Прикольная вещь geoip, распознает страну, к которой айпишник принадлежит.

Для начала качаем набор всего этого добра(например релиз за 30 мая):
ftp://netfilter.org/pub/patch-o-matic-ng/snapshot/patch-o-matic-ng-20050530.tar.bz2

Распаковываем в какую-нить директорию, натягиваем патч:

tar xfz patch-o-matic-ng-XXXXXX.tar.gz
cd patch-o-matic-ng
IPTABLES_DIR=/usr/src/iptables KERNEL_DIR=/usr/src/linux ./runme geoip


У меня прошло ваще без проблем. Затем включаем в ядро появившуюся там опцию "geoip match support", либо как модуль, либо включаем в ядро. Я сделал как модуль. Пересобираем ядро. Потом пересобираем iptables из тех исходников, которые пропатчили.
Еще важный момент - надо положить базу с адресами/странами в /var/geoip/. Именно сюда, т.к. путь вшит в установку iptables, но можно поискать и поменять, наверное База состоит из файлов geoipdb.bin и geoipdb.idx, их надо качнуть из инета. ссылок полно.

Пример пользования:
iptables -A INPUT --dport 25 -m geoip --src-cc RU -j ACCEPT
iptables -A INPUT --dport 25 -j LOG --log-prefix "Blocked smtp from not RU:"
iptables -A INPUT --dport 25 -j REJECT

ну а дальше уже блочим......

BFenix
23.08.2009, 20:03
ну а дальше уже блочим......


PoM уже не актуален. Сейчас лучше юзать xtables (http://xtables-addons.sourceforge.net/)

ReduKToR
24.08.2009, 06:34
ну так я всеголиш ответил на вопрос,я неговорил что актуально,а что нет

BFenix
28.08.2009, 23:42
Есть кто-нить кто может для теста подосить?