Firewall (iptables) (firewall)

Script de firewall

Categoria: Segurança

Software: Firewall (iptables)

[ Hits: 25.808 ]

Por: Marcone Gledson de Almeida


Script de firewall com bloqueios de portas, regras de segurança de rede, liberação de portas específicas, bloqueios a programas P2P e messengers e  regras de redirecionamento (VNC e PcAnyWhere).

Escrito originalmente por Leonardo Pimenta Gonzalez


#! /bin/sh

# /sbin/init.d/<skeleton>
#
#   and symbolic its link
#
### BEGIN INIT INFO
# Provides: firewall
# Required-Start: $network cron
# X-UnitedLinux-Should-Start:
# Required-Stop:
# Default-Start:  3 5
# Default-Stop:
# Description:    FW
### END INIT INFO


# /sbin/rc<skeleton>

. /etc/rc.status

# Shell functions sourced from /etc/rc.status:
#      rc_check         check and set local and overall rc status
#      rc_status        check and set local and overall rc status
#      rc_status -v     ditto but be verbose in local rc status
#      rc_status -v -r  ditto and clear the local rc status
#      rc_failed        set local and overall rc status to failed
#      rc_reset         clear local rc status (overall remains)
#      rc_exit          exit appropriate to overall rc status

LAN=192.168.4.0/24      
NET=eth0

# First reset status of this service
rc_reset
case "$1" in
    start)
   echo -n "Starting Firewall Rules"
   ## Start daemon with startproc(8). If this fails
   ## the echo return value is set appropriate.

   #startproc /usr/sbin/foo

iptables -F
iptables -t nat -F

for module in ip_tables ip_conntrack ip_conntrack_ftp ip_nat_ftp iptable_nat iptable_filter; do
   if ! modprobe $module; then
      echo "Can't load module $module";
      return=$rc_failed
   fi
done

################### CRIA�O DOS LOGS DE ACESSO ######################

# Monitoramento de acessos
iptables -N LACCEPT
iptables -A LACCEPT -j LOG --log-level info --log-prefix "ACCESS: "
iptables -A LACCEPT -j ACCEPT

# Monitoramento de pacotes rejeitados
iptables -N FDROP
iptables -A FDROP -j LOG --log-level debug --log-prefix "FDROP: "
iptables -A FDROP -j DROP

# Monitoramento dos programas VNC e Terminal Server (respectivamente)
iptables -t nat -A PREROUTING -p tcp --dport 5900 -j LOG --log-prefix="VNC:"
iptables -t nat -A PREROUTING -p tcp --dport 3389 -j LOG --log-prefix="Terminal Server:"


################### REGRAS DE SEGURAN� DA REDE ######################

# Descarte de pacotes nao-identificado ICMP (ping)
iptables -A OUTPUT -m state -p icmp --state INVALID -j DROP

# Contra DoS: 
iptables -A FORWARD -p tcp --syn -m limit --limit 1/s -j ACCEPT 

# Contra Port Scanners: 
iptables -A FORWARD -p tcp --tcp-flags SYN,ACK,FIN,RST RST -m limit --limit 1/s -j ACCEPT 

# Contra Pings da morte 
iptables -A FORWARD -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT

# Bloquear Back Orifice: 
iptables -A INPUT -p tcp --dport 31337 -j DROP 
iptables -A INPUT -p udp --dport 31337 -j DROP 

# Bloquear NetBus: 
iptables -A INPUT -p tcp --dport 12345:12346 -j DROP 
iptables -A INPUT -p udp --dport 12345:12346 -j DROP 

################### LIBERACAO DE PORTAS ######################

# Liberacao de acesso SSH para acesso remoto
iptables -A INPUT -p tcp -i $NET \
--dport 22 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

# Liberacao das portas TCP altas (1022 a 65535)
iptables -A INPUT -p tcp -i $NET --dport 1022:65535 \
-m state --state ESTABLISHED,RELATED -j ACCEPT

# Liberacao das portas TCP altas (1022 a 65535)para pesquisa DNS
iptables -A INPUT -p udp -i $NET --sport 53 --dport 1024:65535 \
-m state --state ESTABLISHED -j ACCEPT

# Bloqueio de todas as outras portas
#iptables -A INPUT -i $NET -j FDROP

################ BLOQUEIO DE PROGRAMAS P2P e Messengers ####################

# Bloqueio de MSN Messenger
#iptables -A FORWARD -s 192.168.0.0/24 -p tcp --dport 1863 -j REJECT
#iptables -A FORWARD -s 192.168.0.0/24 -d loginnet.passport.com -j REJECT

# Bloqueio de Kazaa
iptables -A FORWARD -p tcp --dport 1214 -j REJECT 
iptables -A FORWARD -p udp --dport 1214 -j REJECT
iptables -A FORWARD -d 213.248.112.0/24 -j REJECT 
iptables -A FORWARD -d 206.142.53.0/24 -j REJECT 

################# REGRAS DE REDIRECIONAMENTO #################################

# Redirecionamento do Man do Oracle
#iptables -t nat -A PREROUTING -i $NET -p tcp --dport 1158 -m state --state \
#NEW,ESTABLISHED,RELATED  -j DNAT --to 192.168.0.252
#iptables -t nat -A PREROUTING -i $NET -p udp --dport 1158 -m state --state  \
#NEW,ESTABLISHED,RELATED  -j DNAT --to 192.168.0.252

# Redirecionamento do Terminal Server
#iptables -t nat -A PREROUTING -i $NET -p tcp --dport 5900 -m state --state  \
#NEW,ESTABLISHED,RELATED  -j DNAT --to 192.168.0.70

# Regras para redirecionamento de IP para o PCAnywhere
#iptables -t nat -A PREROUTING -i $NET -p tcp -s 201.24.152.2 --dport 5631 -j DNAT \
#--to-destination 192.168.0.70
#iptables -t nat -A PREROUTING -i $NET -p tcp -s 201.24.152.2 --dport 5632 -j DNAT \
#--to-destination 192.168.0.70

# Redirecionamento do VNC
#iptables -t nat -A PREROUTING -i $NET -p tcp --dport 5900 -m state --state  \
#NEW,ESTABLISHED,RELATED  -j DNAT --to 192.168.0.70

############### REGRAS DE PARA COMPARTILHAMENTO DA INTERNET ###################

# Libera�o da LoopBack (127.0.0.1)
iptables -t nat -A POSTROUTING -o lo -j ACCEPT

# Compartilha a Internet
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -s $LAN -j MASQUERADE


# Redirecionamento de porta para Proxy Transparente Squid
#iptables -t nat -A PREROUTING -s $LAN  -p tcp --dport 80 -j REDIRECT --to-port 3128

#####################
   # Remember status and be verbose
   rc_status -v
   ;;
    stop)
   echo -n "Shutting down Firewall Rules"
   ## Stop daemon with killproc(8) and if this fails
   ## set echo the echo return value.

   iptables -F 
   iptables -t nat -F
   #Deletar regras de log
   iptables -X LACCEPT
   iptables -X FDROP

   #killproc -TERM /usr/sbin/foo

   # Remember status and be verbose
   rc_status -v
   ;;
    restart)
   ## If first returns OK call the second, if first or
   ## second command fails, set echo return value.
   $0 stop  &&  $0 start

   # Remember status and be quiet
   rc_status
   ;;
    reload)
   ## Choose ONE of the following two cases:

   ## First possibility: A few services accepts a signal
   ## to reread the (changed) configuration.

   #echo -n "Reload service foo"
   #killproc -HUP /usr/sbin/foo
   #rc_status -v
   ## Exclusive possibility: Some services must be stopped
   ## and started to force a new load of the configuration.

   #$0 stop  &&  $0 start

   # Remember status and be verbose
   #rc_status -v
   ;;
    status)
   echo -n "Checking for Firewall Rules: "
   iptables -nL
   ## Check status with checkproc(8), if process is running
   ## checkproc will return with exit status 0.

   #checkproc /usr/sbin/foo && echo OK || echo No process
   ;;
    *)
   echo "Usage: $0 {start|stop|status}"
   exit 1
   ;;
esac
rc_exit
  


Comentários
[1] Comentário enviado por zeza em 23/05/2007 - 11:11h

vlw cara

[2] Comentário enviado por marcio.moura em 14/06/2007 - 13:30h

muito bom o Artigo, mas vou meter o meu bedelho em uma linha q achei um pequeno engano, ai vai a linha:

Redirecionamento do Terminal Server
#iptables -t nat -A PREROUTING -i $NET -p tcp --dport 5900 -m state --state \
#NEW,ESTABLISHED,RELATED -j DNAT --to 192.168.0.70


a porta correta aqui é 3389

no resto a principio tudo certo muito bom meus parabéns!!!

[3] Comentário enviado por baxman em 14/06/2007 - 14:54h

Marcio..

Vc está correto.. na realidade é a porta 3389

houve um errim ai!

:-)

[4] Comentário enviado por abeljnr em 28/06/2007 - 10:29h

mto bom...

desculpe-me pela minha ignorancia...

mas aonde eu edito td isso?????


se alguem puder me responder no meu email, fic ograto.

obriagdo pela atencao, e espero a resposta...


abeljnr@ig.com.br

[5] Comentário enviado por baxman em 28/06/2007 - 10:43h

na realidade você vai criar um arquivo chamado firewall dentro do diretório
/etc/init.d/. Para fazer isso digite o comando como root.
# touch /etc/init.d/firewall

Aplique as permissões de execução
# chmod +x /etc/init.d/firewall

Copie todo o conteúdo da configuração do firewall todo pra dentro deste arquivo.

Crie os link simbolicos para execução automatica pelo boot
# cd /etc/init.d/rc3.d
# ln -s ../firewall S20firewall
# ln -s ../firewall K20firewall
# cd /etc/init.d/rc5.d
# ln -s ../firewall S20firewall
# ln -s ../firewall K20firewall

[6] Comentário enviado por marceloespindola em 07/07/2007 - 14:54h

Pessoal estou escrevendo um artigo aqui para o viva o linux sobre scrippt de firewall, ele está completo pois levei muito tempo para desenvolve-lo e tinha objetivo de reunir as principais soluções e dúvidas sobre firewall para este artigo, mas como quero construir um bom artigo ainda está em fase de construção para o vivaolinux, entretanto estou disponibilizando no endereço http://marcelolinux.blogspot.com/2007/07/meu-primeiro-artigo-do-vivaolinux.html

os arquivos e o artigo referente a script de firewall completo.

[7] Comentário enviado por faustonet em 25/07/2007 - 12:43h

Como eu faço para ter acesso aos arquivos de log referente ao monitoramento do que foi negado e do que foi permitido?

[8] Comentário enviado por baxman em 31/07/2007 - 08:59h

acesse o messages

tail -f /var/log/messages

se mostrado os logs em tempo real

[9] Comentário enviado por tiulex em 18/09/2007 - 11:47h

pessoal, estou com uma duvida, sera q alguem poderia me ajudar.
na empresa onde trabalho, eu cuido da rede d micros, e analisando o meu firewall eu constatei algo diferente nos logs. sera q alguem poderia me dar uma luz no q pode estar havendo?
a mensagem no log é a seguinte:

Sep 18 08:35:42 kntlan kernel: FIREWALL: squid: IN=eth0 OUT= MAC=00:0c:f1:af:27:75:00:14:a9:88:37:e7:08:00 SRC=202.71.128.103 DST=200.x.x.x LEN=48 TOS=0x00 PREC=0x00 TTL=114 ID=27071 DF PROTO=TCP SPT=3362 DPT=3128 WINDOW=65535 RES=0x00 SYN URGP=0

aguardo uma resposta

[10] Comentário enviado por celsof2 em 26/03/2008 - 05:27h

kra muito bom mesmo

[11] Comentário enviado por comfaa em 28/10/2008 - 10:42h

muito bom !!

[12] Comentário enviado por xerpa em 25/08/2009 - 18:48h

[root@localhost etc]# ./rc.status start
./rc.status: line 20: ./etc/rc.status: No such file or directory
./rc.status: line 35: rc_reset: command not found
Starting Firewall Rulesiptables: Chain already exists
iptables: Chain already exists
./rc.status: line 159: rc_status: command not found
./rc.status: line 215: rc_exit: command not found

+noob aqui hhahahaha alguem pode me dar uma luz ???
nao sei o q acontece


Contribuir com comentário

  



Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts