terça-feira, 19 de junho de 2012

Iptables

Iptables How to Básico

Iptables são uma firewall, instalado de base no Ubuntu Server. Numa instalação regular, as iptables estão instaladas, mas permitem todo o tráfego (assim a firewall esta inactiva)



Comandos Básicos

Escrevendo
# sudo iptables -L
Lista as tuas regras actuais nas iptables. Se acabaste de instalar, não deves ter nenhuma regra, e deverás ver


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


Permitir sessões estabelecidas

Podemos permitir sessões estabelecidas para receber tráfego:
# iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT


Permitir Tráfego de entrar em portas específicas

Podes começar por bloquear tráfego, mas podes estar a trabalhar sobre SSH, então é necessário permitir SSH antes de bloquear o resto.
Para permitir tráfego de entrada na porta 22 (usada tradicionalmente pelo SSH), podes dizer a iptables para permitir todo o tráfego TCP na porta 22 da tua placa de rede.
# iptables -A INPUT -p tcp -i eth0 --dport ssh -j ACCEPT
Especificamente, isto adiciona (-A) a tabela INPUT a regra que qualquer tráfego na interface (-i) eth0 na porta de destino para o ssh que a iptables deverá saltar ("jump" -j), ou realizar a acção ACCEPT (aceitar).
Vamos conferir as regras: (só as primeiras linhas são mostradas, vais ver mais)
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
Agora, vamos permitir todo o tráfego web
# iptables -A INPUT -p tcp -i eth0 --dport 80 -j ACCEPT
Conferir as regras, temos:
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:www
Foi permitido especificamente o tráfego tcp para ssh e porta web, mas ainda não esta nada bloqueado, todo o tráfego pode entrar ainda.


Bloquear Tráfego

Quando uma decisão sobre um pacote é tomaca, outras regras não o afectam. Como as regras para permitir ssh e web vêm primeiro, e se as regras para bloquear tudo estiverem depois delas, pode-se continuar a aceitar o tráfego que queremos. Tudo o que é preciso fazer é colocar no final a regra para bloquear o tráfego todo. O comando -A diz as iptables para adicionar a regra no final, assim vamos usar mais uma vez.
# iptables -A INPUT -j DROP
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:www
DROP       all  --  anywhere             anywhere
Como não foi especificado nenhuma interface ou protocolo, qualquer tráfego em qualquer porta vai ser bloqueado, exepto para web e ssh.


Editar Iptables

O único problema com esta configuração até agora é que até a porta de loopback estar bloqueada. Podiamos só ter escrito as regras de negação só para o eth0 especificando -i eth0, mas pode-se adicionar uma regra para o loopback. Se adicionar-mos essa regra agora, já vem tarde - depois do tráfego já ter sido negado. É preciso adicionar na quarta linha.
# iptables -I INPUT 4 -i lo -j ACCEPT
# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:www
ACCEPT     all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere
As últimas 2 linhas são muito semelhantes, por isso fazemos uma listagem com mais detalhes.
# iptables -L -v


Logging

Nos exemplos em cima nenhum do tráfego era registado. Se queres um log dos pacotes bloqueados para o syslog, está pode ser a forma mais rápida:
In the above examples none of the traffic will be logged. If you would like to log dropped packets to syslog, this would be the quickest way:
# iptables -I INPUT 5 -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
Vê a secção #Dicas para mais ideias sobre logging.

Gravar iptables

If you were to reboot your machine right now, your iptables configuration would disapear. Rather than type this each time you reboot, however, you can save the configuration, and have it start up automatically. To save the configuration, you can use iptables-save and iptables-restore.


Configurar no Startup

Grava as tuas regras da firewall para um ficheiro
# iptables-save > /etc/iptables.up.rules
Depois modifica o script /etc/network/interfaces para aplicar as regras automáticamente ( a última linha é adicionada )
auto eth0
iface eth0 inet dhcp
  pre-up iptables-restore < /etc/iptables.up.rules
Também podes preparar um conjunto de regras de negação de ligações.
You can also prepare a set of down rules and apply it automatically
auto eth0
iface eth0 inet dhcp
  pre-up iptables-restore < /etc/iptables.up.rules
  post-down iptables-restore < /etc/iptables.down.rules


Dicas

Se as iptables são editadas regularmente
Os passos acima descrevem como configurar a tua firewall e presumir que vão ser relativamente estáticas ( e para a maioria deve ser ). Mas se realizas muito trabalho de desenvolvimento, podes querer que as tuas iptables sejam gravadas todas as vezes que reinicias. Para tal, podes-se adicionar uma linha como esta no etc/network/interfaces:
 pre-up iptables-restore < /etc/iptables.up.rules
 post-down iptables-save > /etc/iptables.up.rules
A linha "post-down iptables-save > /etc/iptables.up.rules" irá gravar as regras para ser usadas no próximo boot.
Using iptables-save/restore to test rules
If you edit your iptables beyond this tutorial, you may want to use the iptables-save and iptables-restore feature to edit and test your rules. To do this open the rules file in your favorite text editor (in this example gedit).
# iptables-save > /etc/iptables.test.rules
# gedit /etc/iptables.test.rules
You will have a file that appears similiar to (following the example above):
# Generated by iptables-save v1.3.1 on Sun Apr 23 06:19:53 2006
*filter
:INPUT ACCEPT [368:102354]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [92952:20764374]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
-A INPUT -j DROP
COMMIT
# Completed on Sun Apr 23 06:19:53 2006
Notice that these are iptables commands minus the iptable command. Feel free to edit this to file and save when complete. Then to test simply:
# iptables-restore < /etc/iptables.test.rules
After testing, if you have not added the iptables-save command above to your /etc/network/interfaces remember not to lose your changes:
# iptables-save > /etc/iptables.up.rules
More detailed Logging
For further detail in your syslog you may want create an additional Chain. This will be a very brief example of my /etc/iptables.up.rules showing how I setup my iptables to log to syslog:
# Generated by iptables-save v1.3.1 on Sun Apr 23 05:32:09 2006
*filter
:INPUT ACCEPT [273:55355]
:FORWARD ACCEPT [0:0]
:LOGNDROP - [0:0]
:OUTPUT ACCEPT [92376:20668252]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -j LOGNDROP
-A LOGNDROP -p tcp -m limit --limit 5/min -j LOG --log-prefix "Denied TCP: " --log-level 7
-A LOGNDROP -p udp -m limit --limit 5/min -j LOG --log-prefix "Denied UDP: " --log-level 7
-A LOGNDROP -p icmp -m limit --limit 5/min -j LOG --log-prefix "Denied ICMP: " --log-level 7
-A LOGNDROP -j DROP
COMMIT
# Completed on Sun Apr 23 05:32:09 2006
Note a new CHAIN called LOGNDROP at the top of the file. Also, the standard DROP at the bottom of the INPUT chain is replaceed with LOGNDROP and add protocol descriptions so it makes sense looking at the log. Lastly we drop the traffic at the end of the LOGNDROP chain. The following gives some idea of what is happening:
* --limit sets the number of times to log the same rule to syslog
* --log-prefix "Denied..." adds a prefix to make finding in the syslog easier
* --log-level 7 sets the syslog level to informational (see man syslog for more detail, but you can probably leave this)
Desactivar a firewall
Se for preciso desáctivar a firewall temporariamente, podes apagar as regras usando:
# sudo iptables -F

Nenhum comentário:

Postar um comentário