Главная > Сети > Локальные сети >
FAQ по *nix Firewall

FAQ по *nix Firewall


Запуск маскарадинга для диалап-клиентов

echo 1 > /proc/sys/net/ipv4/ip_forward # без форвардинга не заработает
ipfwadm -F -p deny # запретить всем
ipfwadm -F -a m -S 195.0.0.2/0 -D 0.0.0.0/0 # разрешить адресу 195.0.0.2
ipfwadm -F -a m -S 192.22.22.68/0 -D 0.0.0.0/0 # разрешить адресу 195.0.0.2


Ограничить траффик конкретной машины в сети
while sleep 5
do
ipfw add 111 drop ip from baduser.host.name to any
sleep 15
ipfw delete 111
done


Статистика и accounting
NET-3 HOWTO (razdel "IP Accounting") i "man ipfwadm"


Проброс со своего порта на чужую машину

myhost:82 -- > secondhost:8499
ipfwadm -Fa accept -b -P tcp -S 0/0 82 -D secondIPaddr/32 8499


Настройка пакетного фильтра

Date: 7 May 1998
From: Igor Mikhayliuk

Как-то раз, Среда Май 06 1998 10:06, Dima Volodin писал All:

DV > Нет такого стандарта. Есть такое _умолчание_, что если порт не указан, то
DV > это - 80 в случае http и 443 в случае https. Про вообще же говоря, вот
DV > живой пример из жизни - попавши как-то за фиревол, сконфигуренный одним
DV > умельцем от NT, я никак не мог воспользоваться поиском по CNNовскому
DV > сайту - он у них (у CNN) висит на каком-то левом порту (скажем, 8765).
DV > Раздражало страшно. Пришлось сделать конфигурацию из трех пальцев, ssh и
DV > далекого proxy. Слава богу, что хоть 22 порт открыт был (после некоторого
DV > брызганья слюной с моей стороны).

Злобный какой админ попался, хорошо, хоть не влагостойкий.
;)

DV > Короче, суть в том, что у "не хотящего разбираться с каждой очередной
DV > инетовской прогой" весьма смутное представление о TCP в частности и об IP
DV > вообще, и таки ему надо бы сначала разобраться с предметом, а потом уже
DV > приступать к конфигурению фиреволов.

Это, видимо, заявление из серии: "WinNT админ суксь и мастдай"?

DV > И в менее раздраженном тоне -

Вот это есть хорошо весьма.
:)

DV > окрывать надо все _исходящие_ TСРшные
DV > соединения, входящие же пускать только на конкретные хосты и порты,
DV > на
DV > которых висят публично доступные сервисы. Кроме того, обычно открывают
DV > UDРшный трафик на domain (53), ntp (123), real-чего-то там и т.д. и, для
DV > блезиру, входящий icmp. Чтобы работал ping, надо окрыть и исходящий icmp,
DV > и чтобы работал traceroute - udp на тех верхних портах, которыми он
DV > бесстыдно пользуется. Хотя, насколько я слыхал, MSовский tracert работает
DV > не так, как юниксный traceroute, тут не мне рассказывать. Ну и,
DV > естественно, блокируется весь исходящий трафик с чужими src (это не
DV > столько security, сколько хороший тон), весь входящий трафик на чужой dst
DV > и весь входящий трафик со своим src.

В общем сжато и очень хорошо описал, спасибо.

DV > Скорее всего, чего-то забыл, но тут достаточно народу, чтобы исправить и
DV > дополнить.

А теперь, все-таки уточню, откуда растут ноги у моего исходного письма. Велл
ноун сервайсес на то и велл ноун, чтобы все знали, какие протоколы/порты они
используют. Всем известно, что ФТП по умолчанию использует 21-ый порт, а
некоторым даже известно, что еще и 20-й. Но когда дело доходит до чего-то менее
традиционного, возникает проблема. Она решается путем последовательного чтения
доки, если не помогло, поиска в Инете, на худой конец, с использованием
сниффера. Естественно на это уходят силы и время.
Поэтому мне казалось логичным, что где-нибудь существуют накопленные данные о
том, какие программы что юзают. У меня даже есть подозрение, что в хелпе/доках
на крутой файрволл, сниффер и т.п. такое вполне можно найти. И я попросил
помощи
клуба.
Возможно, нежелание разбираться в каждой принесенной юзером мульке кажется тебе
ламеризмом, но мне жалко тратить на это время. А иногда я просто не знаю, как с
этим справиться. Живой пример - мне уже темечко продолбили с сетевой чатилкой
WinTalk. Штука действительно удобная, но доки к ней вообще нету, с автором
связаться не удалось, весьма ограниченный сниффер, которым я располагаю,
показывает мне только результат - сессию на паре последовательных произвольных
портов за 1024. Как она устанавливает сессию, понятия не имею. Я даже напрягся
и
скачал триалку какого-то монстрообразного сниффера, Guardian Session Wall-3, и
был весьма обрадован, когда обнаружил, что этот монстр, с более, чем
двадцатиметровым дистрибутом благополучно трапает видеоподсистему.
:(
В общем, отнесись с пониманием к тому, что админу НТевой сетки так же сложно
находить инфу/программы, касающиеся WAN, как юниксоиду какой-нибудь DTP пакет.
А человеку, который работает в маленькой фирме и, кроме сетки, ковыряется в
железе, вытирает сопли юзерам, сопровождает ДБ и много чего еще делает по
работе, не всегда хватает времени на глубокое освоение тонкостей сетевого
взаимодействия.
:)

Sentry Port Scan Detector 0.60
Date: 28 May 1998 05:45:05 -0000
From: crowland@psionic.com

Sentry is a port scan detector for Linux, *BSD, and most UNIX variants.
Sentry monitors your systems for port probing activity and will then take
any of the following actions:

1) Log the attacker hostname/IP and ports probed.
2) Run external program.
3) Configure routing table to drop route of attacking host.
4) Configure local packet filter (ipfwadm/ipfw) to drop all packets from
attacking host.
Sentry will now detect and respond to stealth scans against your host from
advanced scanners such as nmap:

http://www.insecure.org/nmap/index.html

* Еще для firewall потребуется *

NAT - Network Address Translation - настраивается в ядре командой
ipfwadm

Отключить роутинг.
Kernel reconfigure

Закрыть входные сервисы.
TCPD

Proxy для httpd, ftp, и т.д.
squid

Proxy для телнета, ftp, X11
TIS fw tollkit

Proxy для произвольного TCP всего
socks5

Пример настройки фильтра IPFWADM

Date: 17 Jun 1998
From: MushyPea

On Tue, 16 Jun 1998, Avery Pennarun wrote:

> Here is the script I use on my home IP masquerade system. It is designed
> to deny everything except what is specifically allowed in some of the
> definitions near the top. Note that there is one fatal problem -- the
> input firewall is changed to allow incoming data back to ports 1024
> through 65535, because any of those might have been used to create an
> _outgoing_ connection (and thus might have data been sent back to them).
> NFS servers might run on one of these high port numbers, so watch out.

I do the following:

1) To make the script more readable, use variables:

ME="a.b.c.d/32"
HI="1024:65535"
ANY="0.0.0.0/0"

2) Use "-y -o" options to log all connection attempts (ie. SYN bit set) to
syslog (you need verbose firewall logging compiled into the kernel), and
accept the packets in both directions for these connections.

2a) Example of a bi-directional service

# SMTP mail traffic
/bin/echo -n "SMTP/"
/sbin/ipfwadm -O -a accept -P tcp -S ${ME} ${HI} -D ${ANY} 25 -y -o
/sbin/ipfwadm -O -a accept -P tcp -S ${ME} ${HI} -D ${ANY} 25
/sbin/ipfwadm -I -a accept -P tcp -S ${ANY} 25 -D ${ME} ${HI}
/sbin/ipfwadm -I -a accept -P tcp -S ${ANY} ${HI} -D ${ME} 25 -y -o
/sbin/ipfwadm -I -a accept -P tcp -S ${ANY} ${HI} -D ${ME} 25
/sbin/ipfwadm -O -a accept -P tcp -S ${ME} 25 -D ${ANY} ${HI}

2b) A tricky one - FTP

# Incoming FTP
/bin/echo -n "FTPin/"
/sbin/ipfwadm -I -a accept -P tcp -S ${ANY} ${HI} -D ${ME} 20:21 -y -o
/sbin/ipfwadm -I -a accept -P tcp -S ${ANY} ${HI} -D ${ME} 20:21
/sbin/ipfwadm -O -a accept -P tcp -S ${ME} 20:21 -D ${ANY} ${HI}

3) Drop everything else - note, the 'without logging' section only applies
if you ever set your interface(s) into promiscuous mode... it's wise not
to log packets to/from elsewhere, otherwise the machine load hits the
roof, and the log file expands rapidly... I found out the hard way. ;)

# Deny everything else
# with logging... (target = me)
/sbin/ipfwadm -I -a deny -S 0/0 -D ${ME} -o
/sbin/ipfwadm -O -a deny -S ${ME} -D 0/0 -o
# without logging... (target != me)
/sbin/ipfwadm -I -a deny -S 0/0 -D 0/0
/sbin/ipfwadm -O -a deny -S 0/0 -D 0/0

Hope that's of some help - oh, one thing - if you decide to use logging,
make sure the logfile is on another partition somewhere, in case someone
floods your box to try and fill up the disk! Logging is worth the effort
- I've detected port scans and other such nasties this way.


Ian.


Ian Marsh
mushypea@dominion.net.uk ... Email
http://www.etchq.demon.co.uk/ ... WWW
http://www.dominion.net.uk/ telnet://dominion.net.uk:2468/ ... Dominion
http://www.alpha4.com/ telnet://alpha4.com:3214/ ... MBa4

Пример от Рыкова

rc.firewall:

ifconfig eth0 promisc
ifconfig eth1 promisc
ifconfig eth1 arp
ifconfig eth0 arp
route add -net default gw 193.232.173.45 dev eth1
brcfg -enable >> /dev/null
ipfwadm -I -f
ipfwadm -O -f
ipfwadm -F -f
ipfwadm -I -a reject -S 0.0.0.0/0.0.0.0 -D 0.0.0.0/0.0.0.0
ipfwadm -I -i accept -S 195.231.183.1/255.255.255.255 -D 0.0.0.0/0.0.0.0
ipfwadm -I -i accept -S 195.231.183.2/255.255.255.255 -D 0.0.0.0/0.0.0.0
ipfwadm -I -i accept -P tcp -S 195.231.183.0/255.255.255.0 ftp telnet -D 0.0.0.0/0.0.0.0
ipfwadm -O -a reject -P tcp -k -S 195.231.183.0/255.255.255.0 -D 0.0.0.0/0.0.0.0 137 138 139


Защита named

From: Adam Sulmicki

One of reasons for presenting is that in all examples shown so far
it seemed that everyone suggested to leave named full-open. However,
it does not always have to be case. Say, if you are running an private
network then you want just to allow named get data transfers from
trusted host and that is all.

[root@eax /root]# cat ipfwadm-named
#!/bin/sh
#allow connection only from trusted named servers
ME="1.2.3.4" # MY ip
NS1="10.20.30.41" # IP of the primary name server
NS2="10.20.30.42" # IP of the secondary name server
NS3="10.20.30.43" # IP of the trietary name server
SRV="domain"
/sbin/ipfwadm -I -f
/sbin/ipfwadm -I -a accept -D ${ME} $SRV -W eth0 -P udp -S $NS1 $SRV
/sbin/ipfwadm -I -a accept -D ${ME} $SRV -W eth0 -P tcp -S $NS1 $SRV
/sbin/ipfwadm -I -a accept -D ${ME} $SRV -W eth0 -P udp -S $NS2 $SRV
/sbin/ipfwadm -I -a accept -D ${ME} $SRV -W eth0 -P tcp -S $NS2 $SRV
/sbin/ipfwadm -I -a accept -D ${ME} $SRV -W eth0 -P udp -S $NS3 $SRV
/sbin/ipfwadm -I -a accept -D ${ME} $SRV -W eth0 -P tcp -S $NS3 $SRV
/sbin/ipfwadm -I -a reject -D ${ME} $SRV -W eth0 -P tcp -o -v -x -e
/sbin/ipfwadm -I -a reject -D ${ME} $SRV -W eth0 -P udp -o -v -x -e


And while we are speaking about named. Here is an example
as someone from "Catholic liberal arts institution" (as per their web
page) connecting to my box. I assume that person was scanning
whole subnet searching for vulnerable versions of named.

О статистике и подсчете траффика
Ставите mrtg, и считаете через smnpget.

"ipfwadm configuration utility"
http://www.ejj.net/~sonny/fwconfig/fwconfig.html

И вообще, для начала ознакомиться с документацией

1. Security Problems in the TCP/IP Protocol Suite
-- S.M. Bellovin then of AT&T
ftp://research.att.com/dist/internet_security/ipext.ps.Z

2. A Weekness in the 4.2 BSD Unix TCP/IP Software
-- R.T. Morris then of AT&T
ftp://research.att.com/dist/internet_security/117.ps.Z

*3.* Network (In)Security Through IP Packet Filtering
-- D. Brent Chapman
ftp://coast.cs.purdue.edu/pub/doc/firewalls/Brent_Chapman_packet_filtering.ps.ZOn the subject of firewall and IP packet filtering just go
to (and read the whole directory):
ftp://coast.cs.purdue.edu/pub/doc/firewalls/

In case of interest, the source of the IP filter that
OpenBSD uses, are at:(claims it runs under linux 2.0.31 too)
http://cheops.anu.edu.au/~avalon/

But one of the best monitoring tools is tcpdump, its
current version being 3.4, and you need libpcap-0.x, to
work. Both of the packages are ready to download from:
ftp://ftp.ee.lbl.gov/tcpdump.tar.Z
ftp://ftp.ee.lbl.gov/libpcap.tar.Z
ftp://ftp.ee.lbl.gov/tcpslice.tar.Z
The last one is for reading files with live snapshots
from your net, these written by tcpdump, at later times,
when needed.
WARN: untar libpcap where your *current untarred* tcpdump
files lie, in other words under the tcpdump-3.4 directory!


Еще один firewall - LRP

From: Rob Bringman
To:
linux-security@redhat.com

I am the Firewall-1 administrator where I work and it has a very nice
GUI tool for defining objects (can be hosts, networks, DNS domains,
groups of hosts, etc.) and a straightforward way of building a
rulebase.

At home I use the LRP with a mini-qmail daemon forwarding the e-mail
via qmqp to the real mailhost, and sshd for remote admin. It has
ipautofw, ipportfw and masquerading.

I really can't think of anything I can do with the Firewall-1 machine
that I can't do with this LRP machine. The whole OS used to fit on a
floppy until I added the mini-qmail and sshd packages. Now it boots
off a small HD and runs only on ramdisks. Except for the GUI and the
price, I'd say they are about equal in terms of power and protection.

I've looked into TIS but never used it. It involved running proxy
daemons on the firewall for telnet ftp and snmp. I like the LRP much
better.

(for those that don't know, LRP is the Linux Router Project. see
http://www.linuxrouter.org/

TCPwrapper: hosts.deny

# /etc/hosts/deny
#
# deny all, send an alert email to root...
ALL : ALL : \
banners /etc/banners/deny : \
spawn ( \
/bin/echo -e "\n\
TCP Wrappers\: Connection Refused\n\
By\: $(uname -n)\n\
Process\: %d (pid %p)\n\
\n\
User\: %u\n\
Host\: %c\n\
Date\: $(date)\n\
" | /bin/mail -s "$(uname -n) wrappers\: %d refused for %c" \
root@localhost ) &

====8<------ end of cut --------------------------

This will deny access to anyone not specifically allowed (from
/etc/hosts.allow), give banners message (specific for the daemon being
called - see the man pages), and generate a very informative mail message
sent to root. (You can add other recipients to that line, btw).

We have found this to be VERY useful here...

[mod: Some remarked that things like "%u" are "client controlled" and
could be used to exploit Tony's system. The manual however claims:

Characters in % expansions that may confuse the shell
are replaced by underscores.

so that should be OK. -- REW]

Но я все же предпочту записывать эти логи в файл а не напрягать свой send-
mail - иначе атакующий повысив частоту попыток завести мою машину.

IPFilter

Как у ipfILTER обнулить статистику без перезагрузки?

ipf -z -f my_ipfilter_rules_file



Для того, чтобы использовать ssh1 & ssh2 одновременно, надо:

1. Поставить ssh-1.2.26 (первым!)
2. Поставить ssh-2.x.x
3. В "sshd2_config" добавить (возможно изменив пути):
Ssh1Compatibility yes
Sshd1Path /usr/sbin/sshd1
4. В "ssh2_config" добавить (возможно изменив пути):
Ssh1Compatibility yes
Ssh1Path /usr/bin/ssh1

Настроить в ssh2 ограничения доступ непросто, поэтому самый простой способ -
запускать его через inetd.conf и доступ регулировать стандартными файлами TCP-wrappera hosts.allow/hosts.deny

/etc/inetd.conf
ssh2 stream tcp nowait root /usr/sbin/tcpd sshd2 -i

/etc/hosts.allow
sshd2 : 123.232.175.0/255.255.255.0, 127.0.0.0/255.0.0.0, 234.567.890.12


Украинская Баннерная Сеть

Главная  Алфавитный индекс  Справка  Добавить FAQ  E-mail
Новости  Поиск по сайту

© УкрFAQ 2009
Сайт создан в системе uCoz