sexta-feira, 10 de fevereiro de 2012

Configurando um Firewall do Linux usando Iptables

Configurando um Firewall do Linux usando Iptables

Visão geral

Esta página irá descrever como eu configurar os scripts de firewall iptable para Linux 2.4 ou posterior. Este não é um How-To, não tentará ensinar-lhe nada sobre IPTables, estes são apenas scripts que você pode usar o que eu sei trabalhar, e trabalhar bem. Esses scripts são o que eu costumo usar quando configurar computadores de firewall.

Os Scripts

Eu uso 3 scripts diferentes para iniciar / desativar os serviços de firewall para Linux.

Um script pre.iptable que vai negar tudo o que vem na Internet. Eu iniciar este antes de qualquer interface de rede chegar a isso, quando a rede subir é protegida no caso, por qualquer motivo, o script de firewall principal falhar para inicializar.

Um script rc.firewall como o script principal para iniciar todo o firewall e serviços necessários para executar disfarçados na rede. Basicamente o que este script vai fazer é permitir que qualquer pessoa na rede interna para acessar todos os serviços de internet, mas ninguém do lado de fora não podem acessar a rede interna, a menos que alguém na rede interna inicia a comunicação.

Finalmente um script para liberar todas as IPTables no desligamento, ou sempre que fazer alterações no script principal.

Para que o IPTables para funcionar corretamente, você deve ter todos os módulos do kernel necessários disponíveis, eles são listados no script rc.iptables principal. A maioria das distribuições de Linux já oferecem estes dentro de kernels padrão.

O Script pre.iptables
################################################################################

#!/bin/sh

######### Script to start firewall support before ethernet card initialize

echo "Starting Pre-Firewalling..."

iptables -F
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

################################################################################
 
Você pode baixar o meu script de pre.iptables aqui.
Como você pode ver, lá realmente não é muito para este script. Tudo o que ele faz basicamente é gotas todo tráfego indo ou saindo da caixa de Linux. Algumas pessoas consideram este comportamento extremamente paranóico, mas isso irá garantir a rede caso o script rc.firewall não será inicializado.
Para usar esse script, o que eu faço é para copiá-lo para o diretório /etc/rc.d/init.d, torná-lo executável (chmod + x pre.iptables), em seguida, vinculá-lo a qualquer runlevel que deseja executá-lo sob. O comando a seguir explica a ligação simbólica.
ln -s /etc/rc.d/init.d/pre.iptables /etc/rc.d/rc3.d/S01preiptables

O Script flsh.iptables
################################################################################

#!/bin/sh

######### Script to flush the firewall tables

echo "Flushing Firewall and Deleting Chains"

iptables -F icmp_packets
iptables -F tcp_packets
iptables -F udpincoming_packets
iptables -F allowed
iptables -F

iptables -X icmp_packets
iptables -X tcp_packets
iptables -X udpincoming_packets
iptables -X allowed

iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

################################################################################

 
Você pode baixar o nosso script de flsh.iptables aqui.
Tudo o que este script faz é se livrar de todas as tabelas personalizadas que você cria com o meu script de rc.firewall, bem como fazendo a ação padrão para descartar todo o tráfego em caixa de Linux. Você deve usar esse script quando você desligar o computador. Você também deve usar esse script sempre que você fizer alterações para o script rc.firewall para que você começa com uma ardósia limpa. O seguinte é um comando para permitir que esse script seja executado cada vez que você desligar o computador. Você também deve fazer um link simbólico para /usr/bin ou em qualquer outro em seu caminho para permitir a fácil liberação do firewall.
ln -s /etc/rc.d/init.d/flsh.iptables /etc/rc.d/rc0.d/S01flshiptables

ln -s /etc/rc.d/init.d/flsh.iptables /usr/bin/flsh.iptables
O Script rc.firewall
#!/bin/sh

###################################
#
# IP Firewall script with NAT for
# Dual-Homed Linux Servers
# Author: Mike Petersen
#
# Updated July 2010 for RHEL
###################################

# Configuration Options

EXTERNAL_INTERFACE="eth0"
LOOPBACK_INTERFACE="lo"
LAN_INTERFACE_1="eth1"
IPTABLES_CMD="/sbin/iptables"

# Load needed 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
/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
# /sbin/modprobe ipt_owner

# Get the IP Addresses for the network cards
IPADDR=`/sbin/ifconfig $EXTERNAL_INTERFACE | grep -i "addr:" | cut -f2 -d: | cut -f1 -d " "`
LAN_IPADDR=`/sbin/ifconfig $LAN_INTERFACE_1 | grep -i "addr:" | cut -f2 -d: | cut -f1 -d " "`
LOCALHOST_IP="127.0.0.1/32"
LAN_BCAST_ADDRESS=`/sbin/ifconfig $LAN_INTERFACE_1 | grep -i "Bcast:" | cut -f3 -d: | cut -f1 -d " "`

##########

echo "Starting Firewalling... "
echo "1" > /proc/sys/net/ipv4/ip_forward
# clear existing Tables/Chains
$IPTABLES_CMD -F
$IPTABLES_CMD -X

########## Set default policies
$IPTABLES_CMD -P INPUT DROP
$IPTABLES_CMD -P OUTPUT DROP
$IPTABLES_CMD -P FORWARD DROP
$IPTABLES_CMD -A INPUT -i $LOOPBACK_INTERFACE -j ACCEPT
$IPTABLES_CMD -A OUTPUT -o $LOOPBACK_INTERFACE -j ACCEPT

########## Prerouting chain - Check for obviously spoofed IP's don't use during testing between private networks
########## add problem Internet IP Addresses here to drop (attempted breakins, etc.)
# $IPTABLES_CMD -t nat -A PREROUTING -i $EXTERNAL_INTERFACE -s 192.168.0.0/24 -j DROP
# $IPTABLES_CMD -t nat -A PREROUTING -i $EXTERNAL_INTERFACE -s 10.0.0.0/8 -j DROP
# $IPTABLES_CMD -t nat -A PREROUTING -i $EXTERNAL_INTERFACE -s 172.16.0.0/12 -j DROP

########## Port Forwarding in Prerouting Chain
# Example of Port Forwarding, first allow the specific FORWARD connection, then reroute it
# $IPTABLES_CMD -A FORWARD -p TCP -i $EXTERNAL_INTERFACE --dport 80 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
# $IPTABLES_CMD -A PREROUTING -p TCP -t nat -d $IPADDR --dport 80 -m state --state NEW,ESTABLISHED,RELATED -j DNAT --to 10.0.0.2:80

########## Drop certain bad packets
$IPTABLES_CMD -N bad_tcp_packets
$IPTABLES_CMD -A bad_tcp_packets -p tcp --tcp-flags SYN,ACK Syn,ACK -m state --state NEW -j REJECT --reject-with tcp-reset
$IPTABLES_CMD -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j LOG --log-prefix "NEW not syn:"
$IPTABLES_CMD -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j DROP
$IPTABLES_CMD -A INPUT -p tcp -j bad_tcp_packets

########## Ensure LAN ADDR aren't blocked
$IPTABLES_CMD -A INPUT -p ALL -i $LAN_INTERFACE_1 -d $LAN_BCAST_ADDRESS -j ACCEPT
$IPTABLES_CMD -A INPUT -p ALL -d $LOCALHOST_IP -j ACCEPT
$IPTABLES_CMD -A INPUT -p ALL -d $LAN_IPADDR -j ACCEPT
$IPTABLES_CMD -A INPUT -p ALL -d $IPADDR -m state --state ESTABLISHED,RELATED -j ACCEPT

########## Create chains for each packet type
########## and filter the packets onto the correct chains.
$IPTABLES_CMD -N icmp_packets
$IPTABLES_CMD -N tcp_packets
$IPTABLES_CMD -N udpincoming_packets
$IPTABLES_CMD -A INPUT -p ICMP -i $EXTERNAL_INTERFACE -j icmp_packets
$IPTABLES_CMD -A INPUT -p TCP -i $EXTERNAL_INTERFACE -j tcp_packets
$IPTABLES_CMD -A INPUT -p UDP -i $EXTERNAL_INTERFACE -j udpincoming_packets

########## The Allowed Chain for TCP connections
$IPTABLES_CMD -N allowed
$IPTABLES_CMD -A allowed -p TCP --syn -j ACCEPT
$IPTABLES_CMD -A allowed -p TCP -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPTABLES_CMD -A allowed -p TCP -j DROP

########## Open ICMP rules (Internet Control Message Protocol)

$IPTABLES_CMD -A icmp_packets -p ICMP -s 0/0 --icmp-type 0 -j ACCEPT
$IPTABLES_CMD -A icmp_packets -p ICMP -s 0/0 --icmp-type 3 -j ACCEPT
$IPTABLES_CMD -A icmp_packets -p ICMP -s 0/0 --icmp-type 5 -j ACCEPT
$IPTABLES_CMD -A icmp_packets -p ICMP -s 0/0 --icmp-type 8 -j ACCEPT
$IPTABLES_CMD -A icmp_packets -p ICMP -s 0/0 --icmp-type 11 -j ACCEPT

########## Open TCP rules (Transmission Control Protocol)
### FTP port
$IPTABLES_CMD -A tcp_packets -p TCP -i $EXTERNAL_INTERFACE -s 0/0 --dport 21 -j allowed
### SSH port
$IPTABLES_CMD -A tcp_packets -p TCP -i $EXTERNAL_INTERFACE -s 0/0 --dport 22 -j allowed
### SMTP Mail Server port
# $IPTABLES_CMD -A tcp_packets -p TCP -i $EXTERNAL_INTERFACE -s 0/0 --dport 25 -j allowed
### DNS port
$IPTABLES_CMD -A tcp_packets -p tcp -i $EXTERNAL_INTERFACE -s 0/0 --dport 53 -j allowed
### HTTP port
# $IPTABLES_CMD -A tcp_packets -p tcp -i $EXTERNAL_INTERFACE -s 0/0 --dport 80 -j allowed
### POP3 port
# $IPTABLES_CMD -A tcp_packets -p TCP -i $EXTERNAL_INTERFACE -s 0/0 --dport 110 -j allowed
### IRC port
# $IPTABLES_CMD -A tcp_packets -p TCP -i $EXTERNAL_INTERFACE -s 0/0 --dport 113 -j allowed
### IMAP port
# $IPTABLES_CMD -A tcp_packets -p TCP -i $EXTERNAL_INTERFACE -s 0/0 --dport 143 -j allowed

########## Open UDP ports (User Datagram Protocol)
### DNS
$IPTABLES_CMD -A udpincoming_packets -p UDP -i $EXTERNAL_INTERFACE -s 0/0 --source-port 53 -j ACCEPT
### NTP
$IPTABLES_CMD -A udpincoming_packets -p UDP -i $EXTERNAL_INTERFACE -s 0/0 --source-port 123 -j ACCEPT
### IMAP
$IPTABLES_CMD -A udpincoming_packets -p UDP -i $EXTERNAL_INTERFACE -s 0/0 --source-port 143 -j ACCEPT

#### Enable to log INPUT errors That didn't match anything above
$IPTABLES_CMD -A INPUT -m limit --limit 3/minute --limit-burst 3 -j LOG --log-level DEBUG --log-prefix "IPT INPUT packet died: "

########## FORWARD RULES
$IPTABLES_CMD -A FORWARD -p tcp -j bad_tcp_packets
$IPTABLES_CMD -A FORWARD -i $LAN_INTERFACE_1 -j ACCEPT
$IPTABLES_CMD -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPTABLES_CMD -A FORWARD -m limit --limit 3/minute --limit-burst 3 -j LOG --log-level DEBUG --log-prefix "IPT FORWARD packet died: "

########## OUTPUT chain # Establish the basic Output chain
$IPTABLES_CMD -A OUTPUT -p tcp -j bad_tcp_packets
$IPTABLES_CMD -A OUTPUT -p ALL -s $LOCALHOST_IP -j ACCEPT
$IPTABLES_CMD -A OUTPUT -p ALL -s $LAN_IPADDR -j ACCEPT
$IPTABLES_CMD -A OUTPUT -p ALL -s $IPADDR -j ACCEPT
$IPTABLES_CMD -A OUTPUT -m limit --limit 3/minute --limit-burst 3 -j LOG --log-level DEBUG --log-prefix "IPT OUTPUT packet died: "

########## Enable SNAT / Masquerading
# If you want to use Masquerading instead of SNAT
# $IPTABLES_CMD -t nat -A POSTROUTING -o $EXTERNAL_INTERFACE -j MASQUERADE
$IPTABLES_CMD -t nat -A POSTROUTING -o $EXTERNAL_INTERFACE -j SNAT --to-source $IPADDR


 
Você pode baixar o nosso script de rc.iptables aqui.

Para fazer isto automaticamente executar na inicialização você poderia fazer um link simbólico de /etc/rc.d/init.d/rc.iptables para /etc/rc.d/rc3.d/S15iptables. Isso deve funcionar para qualquer conexão com a Internet, estática ou DHCP. Apenas certifique-se de que especificar as NICs corretas para cada conexão no script.
Como você pode ver no script, permiti determinados serviços para servidores de acesso para o computador de firewall, como o http ou ssh. Você pode adicionar seus próprios serviços que você deseja permitir o acesso a, apenas experimentar.
 
Retirado de PCC-Services.com.

Sem comentários:

Enviar um comentário