{"id":510,"date":"2013-06-14T00:11:46","date_gmt":"2013-06-14T03:11:46","guid":{"rendered":"http:\/\/blog.abratel.com.br\/?p=510"},"modified":"2013-06-14T00:14:04","modified_gmt":"2013-06-14T03:14:04","slug":"iptables","status":"publish","type":"post","link":"https:\/\/blog.abratel.com.br\/?p=510","title":{"rendered":"Iptables"},"content":{"rendered":"<p>Configurando o Iptables e Fazendo Regras B\u00e1sicas<\/p>\n<p>20 de janeiro de 2004<br \/>\nPostado por: Thadeu Camargo<\/p>\n<p>J\u00e1 est\u00e1 mais do que comprovado: Hoje em dia uma m\u00e1quina sem conex\u00e3o com a internet n\u00e3o tem maior valia do que uma m\u00e1quina de escrever. \u00c9 certo que os micros precisam se conectar para trocar informa\u00e7\u00f5es, ou mesmo somente para baixar um driver para que seu dispositivo de hardware funcione. A partir do momento em que a m\u00e1quina tem uma conex\u00e3o com a internet, est\u00e1 sujeita a ataques de crackers ou scriptie kids. Se um micro pessoal est\u00e1 sujeito a ataques, que dir\u00e1 ent\u00e3o uma rede de computadores. Existem v\u00e1rios sujeitos prontos para se aproveitarem de m\u00e1quinas vulner\u00e1veis. Para evitar intemp\u00e9ries como estas o usu\u00e1rio ou administrador da rede precisa implantar pol\u00edticas de seguran\u00e7a. Uma destas pol\u00edticas \u00e9 a implanta\u00e7\u00e3o de um firewall.<br \/>\nFirewall, como o nome diz, \u00e9 uma porta de fogo. Uma muralha onde somente o que est\u00e1 devidamente autorizado pode entrar ou sair. Maiores detalhes sobre firewall podem ser vistos aqui.<\/p>\n<p>Um sistema bem servido de firewall<\/p>\n<p>Existem firewalls para todos os sistemas operacionais mas creio que nenhum deles esteja t\u00e3o bem servido quanto o Linux. Sem desmerecer outros mas a solu\u00e7\u00e3o Iptables ao meu ver \u00e9 uma das melhores, sen\u00e3o a melhor que eu j\u00e1 vi para seguran\u00e7a de sistemas. A grande vantagem do Iptables \u00e9 a sua estabilidade, rapidez, efici\u00eancia reconhecida e relativa facilidade de administra\u00e7\u00e3o devido a sua configura\u00e7\u00e3o poder ser feita atrav\u00e9s de scripts. Outras caracter\u00edsticas do Iptables:<\/p>\n<p>.: Suporte aos protocolos TCP, UDP, ICMP<br \/>\n.: Pode se especificar portas de endere\u00e7o e de destino.<br \/>\n.: Suporta m\u00f3dulos externos como FTP e IRC<br \/>\n.: Suporta um n\u00famero ilimitado de regras por CHAINS ( correntes ).<br \/>\n.: Pode se criar regras de prote\u00e7\u00e3o contra ataques diversos<br \/>\n.: Suporte para roteamento de pacotes e redirecionamento de portas.<br \/>\n.: Suporta v\u00e1rios tipos de NAT, como o SNAT e DNAT e mascaramento.<br \/>\n.: Pode priorizar tr\u00e1fego para determinados tipos de pacotes.<br \/>\n.: Entre outras o Iptables j\u00e1 tem suporte a IPV6, atrav\u00e9s do programa ip6tables.<\/p>\n<p>O Iptables acompanha o kernel 2.4.x. Antes dele existia o Ipchains ( kernel 2.2.x ) e anteriormente ainda existia o Ipfwadm. Na realidade no kernel 2.4.x ainda existem os filtros Ipchains e Ipfwadm por motivos de compatibilidade mas ambos n\u00e3o est\u00e3o ativos. Caso estejam ativos ( isto pode acontecer com o Ipchains ) \u00e9 necess\u00e1rio desativ\u00e1-los para que o Iptables possa funcionar plenamente.<\/p>\n<p>Funcionamento<\/p>\n<p>Atrav\u00e9s de regras poderemos fazer com que os pacotes possam ser ou n\u00e3o recebidos a rede toda, a determinada m\u00e1quina, interface ou mesmo porta de conex\u00e3o. O Iptables trabalha atrav\u00e9s de Tabelas, Chains e Regras:<\/p>\n<p>Tabelas: Existem 3 tabelas poss\u00edveis de serem utilizadas no Iptables, sendo que uma delas, a mangle raramente \u00e9 usada, restando a filter, que \u00e9 a padr\u00e3o, utilizada nos tr\u00e1fegos de dados comuns, sem ocorr\u00eancia de NAT. Quando n\u00e3o especificamos qual tabela a ser utilizada \u00e9 ela que ser\u00e1 ativada. A outra geralmente utilizada \u00e9 a nat, que como o pr\u00f3prio nome diz, usada quando h\u00e1 ocorr\u00eancia de NAT.<\/p>\n<p>Chains: Atrav\u00e9s delas podemos especificar a situa\u00e7\u00e3o do tratamento dos pacotes, seja qual tabela for.<br \/>\nQuando utilizamos a tabela nat as Chains poss\u00edveis s\u00e3o:<br \/>\nPREROUTING \u2013 Quando os pacotes entram para sofrerem NAT.<br \/>\nPOSTROUTING \u2013 Quando os pacotes est\u00e3o saindo ap\u00f3s sofrerem NAT<br \/>\nOUTPUT \u2013 Pacotes que s\u00e3o gerados na pr\u00f3pria m\u00e1quina e que sofrer\u00e3o NAT<br \/>\nJ\u00e1 com a tabela filter as Chains s\u00e3o:<br \/>\nINPUT &#8211; Pacotes cujo destino final \u00e9 a pr\u00f3pria m\u00e1quina firewall.<br \/>\nOUTPUT \u2013 Pacotes que saem da m\u00e1quina firewall<br \/>\nFORWARD \u2013 Pacote que atravessa a m\u00e1quina firewall, cujo destino \u00e9 uma outra m\u00e1quina. Este pacote n\u00e3o sai da m\u00e1quina firewall e sim de outra m\u00e1quina da rede ou fonte. Neste caso a m\u00e1quina firewall est\u00e1 repassando o pacote.<\/p>\n<p>Regras: As regras de firewall geralmente s\u00e3o compostas de uma Tabela, Op\u00e7\u00e3o, Chain, Dados e A\u00e7\u00e3o. Atrav\u00e9s destes elementos podemos especificar o que fazer com os pacotes.<br \/>\nOp\u00e7\u00f5es:<br \/>\n-P<br \/>\nDefine uma regra padr\u00e3o<br \/>\n  -A<br \/>\n                             Acrescenta uma nova regra as existentes.<br \/>\n                                Este tem prioridade sobre a -P<br \/>\n  -D<br \/>\n                                                 Apaga-se uma regra<br \/>\n  -L<br \/>\n                                            Lista as regras existentes<br \/>\n  -F<br \/>\n                                             Apaga todas as regras<br \/>\n  -I<br \/>\n                                            Insere uma regra nova<br \/>\n  -h<br \/>\n                                     Muito \u00fatil, pois mostra a ajuda<br \/>\n  -R<br \/>\n                                              Substitui uma regra<br \/>\n  -C<br \/>\n                            Faz uma checagem das regras existentes<br \/>\n  -Z<br \/>\n                                         Zera uma regra espec\u00edfica<br \/>\n  -N<br \/>\n                                  Cria uma nova regra com um nome<br \/>\n  -X<br \/>\n                           Exclui uma regra espec\u00edfica pelo seu nome<\/p>\n<p>Dados:<br \/>\n-s : Especifica o origem do pacote. Este pode ser tanto uma rede ou host. Poss\u00edveis combina\u00e7\u00f5es podem ser:<br \/>\n-s 192.168.0.0\/255.255.255.0<br \/>\nou<br \/>\n-s 192.168.0.0\/24<br \/>\nOBS: No segundo caso estamos especificando a m\u00e1scara de rede conforme o n\u00famero de bits 1, por exemplo:<br \/>\nM\u00e1scara de rede 255.0.0.0 = 8<br \/>\nM\u00e1scara de rede 255.255.0.0 = 16<br \/>\nM\u00e1scara de rede 255.255.255.0 = 24<\/p>\n<p>No exemplo acima estamos especificando toda uma rede de m\u00e1scara C, no exemplo abaixo especificamos um host:<br \/>\n-s 192.168.30.51\/255.255.255.255<br \/>\nou<br \/>\n-s 192.168.30.51<br \/>\ntamb\u00e9m pode ser assim:<br \/>\n-s 192.168.30.51\/32<br \/>\nOBS: A m\u00e1scara em n\u00fameros de bits 1 para host \u00e9 32.<\/p>\n<p>Podemos especificar assim tamb\u00e9m:<br \/>\n-s www tccamargo.com<\/p>\n<p>Podemos especificar qualquer origem tamb\u00e9m:<br \/>\n-s 0.0.0.0\/0.0.0.0<br \/>\nou<br \/>\n-s 0\/0<\/p>\n<p>-d : Especifica o destino do pacote. A sintaxe \u00e9 a mesma do -s<\/p>\n<p>-p : Protocolo usado na regra. Pode ser tcp, udp, icmp:<br \/>\n-p tcp<br \/>\n-p udp<br \/>\n-p icmp<\/p>\n<p>-i : Interface de entrada, ou seja, placa de rede, modem ou interface de conex\u00e3o que estar\u00e1 recebendo o pacote a ser tratado.<br \/>\n-i eth0<br \/>\n-i eth1<br \/>\n-i ppp0<\/p>\n<p>-o : Interface de sa\u00edda. As sintaxes s\u00e3o as mesmas que -i, sendo que neste caso estar\u00e1 enviando o pacote a ser tratado.<\/p>\n<p>! : Exclui determinado argumento:<br \/>\n-i ! eth0 &#8211; Refere-se a qualquer interface de entrada exceto a eth0<br \/>\n-s ! 192.168.0.45 \u2013 Refere-se a qualquer endere\u00e7o de entrada exceto o 192.168.0.45<\/p>\n<p>&#8211;sport : Refere-se a porta de origem. Este deve vir acompanhado das fun\u00e7\u00f5es -p tcp e -p udp :<br \/>\n-p tcp \u2013sport 80 \u2013 Refere-se a porta de origem 80 sob protocolo tcp<\/p>\n<p>&#8211;dport : Refere-se a porta de destino. Assim como a fun\u00e7\u00e3o \u2013sport, ela trabalha somente com a -p tcp e -p udp. A sintaxe \u00e9 similar a \u2013sport<\/p>\n<p>Atrav\u00e9s das fun\u00e7\u00f5es \u2013sport e \u2013dport podemos especificar n\u00e3o s\u00f3 uma porta espec\u00edfica como tamb\u00e9m um range de portas:<br \/>\n&#8211;sport 33435:33525<\/p>\n<p>A\u00e7\u00f5es:<br \/>\nAs a\u00e7\u00f5es sempre vem ap\u00f3s o par\u00e2metro -j e geralmente s\u00e3o:<br \/>\nACCEPT \u2013 Aceita e permite a passagem do pacote.<br \/>\nDROP \u2013 N\u00e3o permite a passagem do pacote e abandona-o n\u00e3o dando sinais de recebimento.<br \/>\nREJECT \u2013 Assim como o DROP, n\u00e3o permite a passagem do pacote, mas envia um aviso ( icmp unreachable )<br \/>\nLOG \u2013 Cria um Log referente a regra em \/var\/log\/messages<\/p>\n<p>Com estes fatores podemos criar as nossas regras com a seguinte composi\u00e7\u00e3o:<br \/>\n# iptables -A FORWARD -s 192.168.0.45 -p icmp -j DROP<br \/>\nSendo: -A ( op\u00e7\u00e3o ) \/ FORWARD ( Chain ) \/ -s 192.168.0.45 -p icmp ( Dados ) -j DROP ( A\u00e7\u00e3o )<\/p>\n<p>No caso do exemplo a cima a regra determina que todos os pacotes icmp origin\u00e1rios do endere\u00e7o 192.168.0.45 devem ser barrados.<\/p>\n<p>Salvando as regras<\/p>\n<p>Depois das regras prontas podemos salv\u00e1-las com este comando:<br \/>\n# iptables-save > <d\u00ea um nome para o arquivo><\/p>\n<p>Para recuper\u00e1-las use este comando:<br \/>\n# iptables-restore > <nome do arquivo><\/p>\n<p>Outra forma seria fazer um script com as regras:<br \/>\nCorpo do Script<br \/>\n#!\/bin\/bash<br \/>\n#limpando tabelas<br \/>\niptables -F &#038;&#038;<br \/>\niptables -X &#038;&#038;<br \/>\niptables -t nat -F &#038;&#038;<br \/>\niptables -t nat -X &#038;&#038;<br \/>\n#liberando acesso interno da rede<br \/>\niptables -A INPUT -p tcp &#8211;syn -s 192.168.1.0\/255.255.255.0 -j ACCEPT &#038;&#038;<br \/>\niptables -A OUTPUT -p tcp &#8211;syn -s 192.168.1.0\/255.255.255.0 -j ACCEPT &#038;&#038;<br \/>\niptables -A FORWARD -p tcp &#8211;syn -s 192.168.1.0\/255.255.255.0 -j ACCEPT &#038;&#038;<br \/>\n#compartilhando a web na rede interna<br \/>\niptables -t nat -A POSTROUTING -s 192.168.1.0\/255.255.255.0 -o eth1 -j MASQUERADE &#038;&#038;<br \/>\necho 1 > \/proc\/sys\/net\/ipv4\/ip_forward &#038;&#038;<br \/>\n# Protecao contra port scanners ocultos<br \/>\niptables -A INPUT -p tcp &#8211;tcp-flags SYN,ACK,FIN,RST RST -m limit &#8211;limit 1\/s -j ACCEPT<br \/>\n# Bloqueando tracertroute<br \/>\niptables -A INPUT -p udp -s 0\/0 -i eth1 &#8211;dport 33435:33525 -j DROP<br \/>\n#Protecoes contra ataques<br \/>\niptables -A INPUT -m state &#8211;state INVALID -j DROP<br \/>\n#termina<br \/>\necho &#8220;Iptables Pronto&#8221;<\/p>\n<p>Salve-o com um nome sugestivo, como por exemplo \u201cstart-firewall\u201d.<br \/>\nD\u00ea permiss\u00e3o de execu\u00e7\u00e3o:<br \/>\nchmod +x start-firewall<\/p>\n<p>Pronto. Toda vez que quiser que ele seja habilitado \u00e9 s\u00f3 execut\u00e1-lo ( sempre como root ):<br \/>\n# start-firewall<\/p>\n<p>Para n\u00e3o ter que ficar chamando o script toda vez que inicializar o sistema, podemos fazer com que ele seja ativado na inicializa\u00e7\u00e3o. Para isso \u00e9 preciso editar o arquivo<br \/>\n\/etc\/rc.d\/rc.local e incluir o comando no final do arquivo.:-)<\/p>\n<p>Compartilhamento de conex\u00e3o, mascaramento e redirecionamento de pacotes<\/p>\n<p>Verifique que nestas linhas do script exemplo:<br \/>\niptables -t nat -A POSTROUTING -s 192.168.1.0\/255.255.255.0 -o eth1 -j MASQUERADE &#038;&#038;<br \/>\necho 1 > \/proc\/sys\/net\/ipv4\/ip_forward &#038;&#038;<\/p>\n<p>Estou fazendo com que os micros de minha rede possam utilizar a internet atrav\u00e9s do roteamento din\u00e2mico. A linha que habilita o redirecionamento de pacotes \u00e9 essa:<br \/>\necho 1 > \/proc\/sys\/net\/ipv4\/ip_forward<br \/>\nMas vale observar que se inserirmos somente esta linha no script, a cada vez que reiniciar o sistema ser\u00e1 necess\u00e1ria a ativa\u00e7\u00e3o do roteamento. Para que n\u00e3o percamos o roteamento \u00e9 necess\u00e1rio editar o arquivo \/etc\/sysctl.conf e inserirmos ou modificarmos a linha do modo que fique assim:<br \/>\nnet.ipv4.ip_forward= 1<\/p>\n<p>Voltando a nossa regra do script exemplo, verificamos uma a\u00e7\u00e3o nova ( MASQUERADE ), servindo para que as m\u00e1quinas da rede interna possam acessar a internet usando o IP externo do Gateway. Deste modo as m\u00e1quinas da rede interna ficar\u00e3o invis\u00edveis para a rede externa. Para que uma m\u00e1quina da rede interna possa executar servi\u00e7os onde cuja execu\u00e7\u00e3o necessita que o IP da m\u00e1quina seja vis\u00edvel para redes externas, ser\u00e1 necess\u00e1rio fazer um redirecionamento de IPs ou portas.<br \/>\nDigamos que uma m\u00e1quina de IP 192.168.0.45 precise executar um servi\u00e7o de FTP, na qual \u00e9 necess\u00e1ria a visibilidade da m\u00e1quina. Podemos fazer com que a m\u00e1quina firewall, cujo IP externo seja 200.135.100.102 receba estes pacotes e retransmita:<br \/>\niptables -t nat -A PREROUTING -s 200.135.100.102 -i eth0 -j DNAT \u2013to 192.168.0.45<br \/>\niptables -t nat -A POSTROUTING -s 200.135.100.102 -o eth0 -p tcp \u2013dport 21 -j ACCEPT<br \/>\niptables -t nat -A POSTROUTING -s 192.168.0.45 -o eth0 -j SNAT \u2013to 200.135.100.102<br \/>\niptables -t nat -A POSTROUTING -s 192.168.0.45 -o eth0 -p tcp \u2013dport 21 -j ACCEPT<\/p>\n<p>Veja que nestas regras temos mais duas a\u00e7\u00f5es novas SNAT e DNAT:<br \/>\nSNAT \u2013 Aplicada quando queremos alterar o endere\u00e7o de origem do pacote. Aqui n\u00f3s utilizamos para fazer o mascaramento. OBS: Somente a Chain POSTROUTING pode ser usada na a\u00e7\u00e3o SNAT.<br \/>\nDNAT \u2013 Aplicada quando desejamos alterar o endere\u00e7o de destino do pacote. Esta a\u00e7\u00e3o \u00e9 utilizada para fazer redirecionamento de portas, redirecionamento de servidor, load balance e proxy transparente. As Chains que podem ser utilizadas para esta a\u00e7\u00e3o s\u00e3o PREROUTING e OUTPUT.<br \/>\nAl\u00e9m destas duas a\u00e7\u00f5es, existe tamb\u00e9m a REDIRECT que pode ser utilizada para fazer redirecionamento de portas. Quando fazemos um redirecionamento de portas usamos o dado \u2013to-port ap\u00f3s a a\u00e7\u00e3o REDIRECT:<br \/>\niptables -t nat -A PREROUTING -i eth0 -p tcp &#8211;dport 80 -j REDIRECT \u2013to-port 3128<br \/>\n#Esta regra faz com que todos os pacotes direcionados a porta tcp 80 sejam redirecionados para a porta 3128.<br \/>\nQuando utilizamos a tabela nat, \u00e9 preciso inserir o par\u00e2metro -t para especificar a tabela:<br \/>\n-t nat<br \/>\nPerceba que quando omitimos este par\u00e2metro usamos a tabela filter por padr\u00e3o.<br \/>\nAl\u00e9m destas a\u00e7\u00f5es, veja que existe tamb\u00e9m um dado novo:<br \/>\n&#8211;to : Este dado serve para definir o IP ou porta de destino numa a\u00e7\u00e3o SNAT ou DNAT:<br \/>\niptables -t nat -A PREROUTING -p tcp -d 200.135.100.102 \u2013dport 80 -j DNAT \u2013to 192.168.0.45<br \/>\n# Esta regra faz com que os pacotes direcionados a porta tcp 80 sejam redirecionados para a m\u00e1quina 192.168.0.45 . Como n\u00e3o especificamos a porta, a m\u00e1quina de destino receber\u00e1 o pacote na porta 80<br \/>\nAl\u00e9m do IP podemos definir a porta deste endere\u00e7o na a\u00e7\u00e3o:<br \/>\niptables -t nat -A PREROUTING -p tcp -d 200.135.100.102 \u2013dport 80 -j DNAT \u2013to 192.168.0.45:3128<br \/>\n# Aqui, assim como na regra anterior, os pacotes s\u00e3o redirecionados para a m\u00e1quina 192.168.0.45 mas neste caso especificamos a porta, ou seja, porta 3128<\/p>\n<p>Algumas op\u00e7\u00f5es e observa\u00e7\u00f5es<\/p>\n<p>Vale fazer umas pequenas observa\u00e7\u00f5es a respeito da ordem das regras e manejo. Uma delas \u00e9 que a a primeira regra tem prioridade sobre a segunda caso ambas estejam em conflito, veja:<br \/>\niptables -A FORWARD -p tcp &#8211;syn -s 192.168.1.0\/24 -j ACCEPT<br \/>\niptables -A FORWARD -p tcp &#8211;syn -s 192.168.1.0\/24 -j DROP<\/p>\n<p>A que ter\u00e1 valia ser\u00e1 a primeira, ou seja:<br \/>\niptables -A FORWARD -p tcp &#8211;syn -s 192.168.1.0\/24 -j ACCEPT<\/p>\n<p>Podemos ver todas as regras em andamento ao darmos o comando:<br \/>\niptables -L<\/p>\n<p>Com os comandos abaixo limpamos todas as tabelas e regras:<br \/>\niptables -F<br \/>\niptables -X<br \/>\niptables -t nat -F<br \/>\niptables -t nat -X<\/p>\n<p>Para que tudo possa funcionar a contento \u00e9 necess\u00e1rio primeiramente que todos os m\u00f3dulos necess\u00e1rios estejam carregados:<br \/>\nmodprobe ip_conntrack<br \/>\nmodprobe ip_conntrack_ftp<br \/>\nmodprobe ip_nat_ftp<br \/>\nmodprobe ip_queue<br \/>\nmodprobe ip_tables<br \/>\nmodprobe ipt_LOG<br \/>\nmodprobe ipt_MARK<br \/>\nmodprobe ipt_MASQUERADE<br \/>\nmodprobe ipt_MIRROR<br \/>\nmodprobe ipt_REDIRECT<br \/>\nmodprobe ipt_REJECT<br \/>\nmodprobe ipt_TCPMSS<br \/>\nmodprobe ipt_TOS<br \/>\nmodprobe ipt_limit<br \/>\nmodprobe ipt_mac<br \/>\nmodprobe ipt_mark<br \/>\nmodprobe ipt_multiport<br \/>\nmodprobe ipt_owner<br \/>\nmodprobe ipt_state<br \/>\nmodprobe ipt_tcpmss<br \/>\nmodprobe ipt_tos<br \/>\nmodprobe ipt_unclean<br \/>\nmodprobe iptable_filter<br \/>\nmodprobe iptable_mangle<br \/>\nmodprobe iptable_nat<\/p>\n<p>\u00c9 importante ressaltar que as regras devem seguir uma ordem definida, ou seja, a regra posterior deve estar de acordo com a regra anterior para que tudo corra sem problemas.:<br \/>\niptables -P FORWARD -j DROP<br \/>\niptables -A FORMARD -s 192.168.0.0\/24 -d 10.0.0.0\/8 -j ACCEPT<\/p>\n<p>Atrav\u00e9s desta regra, determinamos que todo o repasse de pacotes seja bloqueado, depois permitimos que possa repassar pacotes da rede 192.168.0.0 para a rede 10.0.0.0 mas esta n\u00e3o poder\u00e1 retornar os pacotes. Ent\u00e3o o correto seria inserir mais uma regra aqui:<br \/>\niptables -A FORWARD -d 192.168.0.0\/24 -s 10.0.0.0\/8 -j ACCEPT<\/p>\n<p>Para que a rede 10.0.0.0 possa repassar os pacotes, fazendo deste jeito com que as redes possam conversar sem problemas.<br \/>\nAo fazer as regras lembre-se de primeiro bloquear, depois abrir o acesso.:<br \/>\niptables -P FORMARD -j DROP<br \/>\niptables -A FORWARD -s 192.168.0.45 -p tcp \u2013sport 80 -j ACCEPT<\/p>\n<p>Considera\u00e7\u00f5es finais<\/p>\n<p>Iptables tem infinitas possibilidades de regras. \u00c9 imposs\u00edvel citar todos os par\u00e2metros e regras que podem ser utilizados, pois daria uma verdadeira b\u00edblia. Cabe ao bom administrador estudar com afinco para poder aplicar as regras mais convenientes para a sua rede. E o usu\u00e1rio final tem em m\u00e3os um excelente recurso para deixar sua m\u00e1quina protegida de ataques externos. Esta \u00e9 a grande vantagem do Iptables, pode se aplicar regras conforme a conveni\u00eancia da rede e usu\u00e1rios. Sem d\u00favida nenhuma \u00e9 uma ferramenta poderos\u00edssima.<\/p>\n<p>Exemplos de regras comumente utilizadas<\/p>\n<p>Nas linhas abaixo inclu\u00ed algumas regras que s\u00e3o comumente utilizadas. Algumas destas podem ser \u00fateis para fazer o seu firewall mas lembre-se de adapt\u00e1-las para sua rede\/interface\/m\u00e1quina antes de aplic\u00e1-las:<\/p>\n<p>#Libera o apache pra web<br \/>\niptables -A INPUT -p tcp &#8211;destination-port 6080 -j ACCEPT<br \/>\niptables -A INPUT -p tcp &#8211;destination-port 443 -j ACCEPT<br \/>\n#Libera o loopback<br \/>\niptables -A OUTPUT -p tcp &#8211;syn -s 127.0.0.1\/255.0.0.0 -j ACCEPT<br \/>\n#Bloqueando todos os endere\u00e7os vindo de uma determinada rede para a minha m\u00e1quina<br \/>\niptables -A INPUT -s 10.0.0.0\/8 -j DROP<br \/>\n#Liberando o endere\u00e7o vindo de uma rede para a minha m\u00e1quina<br \/>\niptables -A INPUT -s 10.0.0.1 -j ACCEPT<br \/>\n#Gerando Logs de Portas proibidas<br \/>\niptables -A INPUT -p tcp &#8211;dport 21 -j &#8211;log-prefix &#8220;Servi\u00e7o de FTP&#8221;<br \/>\n#Gerando log de Backdoors<br \/>\niptables -A INPUT -p tcp &#8211;dport 5042 -j LOG -log-prefix &#8220;Wincrash&#8221;<br \/>\niptables -A INPUT -p tcp &#8211;dport 12345 -j LOG -log-prefix &#8220;backOrifice&#8221;<br \/>\niptables -A INPUT -p tcp &#8211;dport 12346 -j LOG -log-prefix &#8220;backOrifice&#8221;<br \/>\n#Habilitando porta de FTP<br \/>\niptables -A INPUT -p tcp -s 192.168.0.45 &#8211;dport 21 -j ACCEPT<br \/>\n#Habilitando porta de SSH<br \/>\niptables -A INPUT -p tcp -s 192.168.0.45 &#8211;dport 22 -j ACCEPT<br \/>\n#Habilitando porta de SMTP<br \/>\niptables -A INPUT -p tcp -s 192.168.0.45 &#8211;dport 25 -j ACCEPT<br \/>\n#Habilitando porta de DNS<br \/>\niptables -A INPUT -p tcp -s 192.168.0.45 &#8211;dport 53 -j ACCEPT<br \/>\n#Habilitando porta de POP3<br \/>\niptables -A INPUT -p tcp -s 192.168.0.45 &#8211;dport 110 -j ACCEPT<br \/>\n#Habilitando porta de DNS (UDP)<br \/>\niptables -A INPUT -p udp -s 192.168.0.45 &#8211;source-port 53 -j ACCEPT<br \/>\n#Redirecionar Porta<br \/>\niptables -t nat -A PREROUTING -s IP_NET -i EXT_INT -j DNAT &#8211;to IP_DESTINO<br \/>\niptables -t nat -A POSTROUTING -s IP_NET -o EXT_INT -p tcp &#8211;dport PORT -j ACCEPT<br \/>\niptables -t nat -A POSTROUTING -s IP_DESTINO -o EXT_INT -j SNAT &#8211;to IP_NET<br \/>\niptables -t nat -A POSTROUTING -s IP_DESTINO -o EXT_INT &#8211;p tcp &#8211;dport PORT -j ACCEPT<br \/>\nIP_NET = IP v\u00e1lido da internet.<br \/>\nEXT_INT = Interface da Internet.<br \/>\nIP_DESTINO = IP inv\u00e1lido da Internet ou melhor ip da rede que vai fazer redirecionamento.<br \/>\nPORT = porta<br \/>\n#Fazendo redirecionamento de portas<br \/>\niptables -t nat -A PREROUTING -i FACE -p tcp &#8211;dport 80 -j REDIRECT &#8211;to-port 3128<br \/>\nFACE = interface de rede<br \/>\n#Bloqueando todos os pacotes origin\u00e1rios da rede 10.0.0.0 para o host www.tccamargo.com<br \/>\niptables -A FORWARD -s 10.0.0.0\/8 -d www.tccamargo.com -j DROP<br \/>\n#Liberando todos os pacotes origin\u00e1rios da rede 10.0.0.0 para o host www.tccamargo.com<br \/>\niptables -A FORWARD -s 10.0.0.0\/8 -d www.tccamargo.com -j ACCEPT<br \/>\n#Liberando todos os pacotes tcp destinados a porta 25<br \/>\niptables -A FORWARD -p tcp &#8211;dport 25 -j ACCEPT<br \/>\n#Liberando acesso interno da rede<br \/>\niptables -A INPUT -p tcp &#8211;syn -s 192.168.1.0\/24 -j ACCEPT<br \/>\niptables -A OUTPUT -p tcp &#8211;syn -s 192.168.1.0\/24 -j ACCEPT<br \/>\niptables -A FORWARD -p tcp &#8211;syn -s 192.168.1.0\/24 -j ACCEPT<br \/>\n#compartilhando a web na rede interna<br \/>\niptables -t nat -A POSTROUTING -s 192.168.1.0\/255.255.255.0 -o eth1 -j MASQUERADE<br \/>\necho 1 > \/proc\/sys\/net\/ipv4\/ip_forward &#038;&#038;<br \/>\n#Libera Bittorrent somente para esta maquina<br \/>\niptables -A INPUT -p tcp &#8211;destination-port 6881:6889 -j ACCEPT<br \/>\n#Bloqueando tracertroute<br \/>\niptables -A INPUT -p udp -s 0\/0 -i eth1 &#8211;dport 33435:33525 -j DROP<br \/>\n#Protecoes contra ataques<br \/>\niptables -A INPUT -m state &#8211;state INVALID -j DROP<br \/>\n#Bloqueando uma m\u00e1quina pelo endere\u00e7o MAC<br \/>\niptables -A INPUT -m mac &#8211;mac-source XX:XX:XX:XX:XX:XX -j DROP<br \/>\n#Prote\u00e7\u00e3o contra IP Spoofing<br \/>\niptables -A INPUT -s 172.16.0.0\/16 -i ext_face -j DROP<br \/>\niptables -A INPUT -s 192.168.0.0\/24 -i ext_face -j DROP<br \/>\niptables -A INPUT -s 192.168.0.0\/24 -i ext_face -j DROP<br \/>\n< ext_face = S\u00e3o as interfaces da internet como ppp e ethX ><br \/>\n#Prote\u00e7\u00e3o contra Syn-floods<br \/>\niptables -A FORWARD -p tcp &#8211;syn -m limit &#8211;limit 1\/s -j ACCEPT<br \/>\n#Prote\u00e7\u00e3o contra port scanners ocultos<br \/>\niptables -A FORWARD -p tcp &#8211;tcp-flags SYN,ACK,FIN,RST RST -m limit &#8211;limit 1\/s -j ACCEPT<br \/>\n#Prote\u00e7\u00e3o contra ping da morte<br \/>\niptables -A FORWARD -p icmp &#8211;icmp-type echo-request -m limit &#8211;limit 1\/s -j ACCEPT<br \/>\n#Bloqueando ping de um ip<br \/>\niptables -A INPUT -p icmp -s 192.168.1.1\/24 -j DROP<br \/>\n#Bloqueando pacotes fragmentados<br \/>\niptables -A INPUT -i INTEXT -m unclean -j log_unclean<br \/>\niptables -A INPUT -f -i INTEXT -j log_fragment<br \/>\n< INTEXT = Interface da INTERNET ><br \/>\n#Anulando as respostas a ICMP 8 (echo reply)<br \/>\necho 1 > \/proc\/sys\/net\/ipv4\/icmp_echo_ignore_all<\/p>\n<p>================================================================<\/p>\n<p>Linux IPTables: Incoming and Outgoing Rule Examples (SSH and HTTP)<br \/>\nby RAMESH NATARAJAN on MARCH 15, 2011<\/p>\n<p>In our previous IPTables firewall series article, we reviewed how to add firewall rule using \u201ciptables -A\u201d.<\/p>\n<p>We also explained how to allow incoming SSH connection. On a high-level, it involves following 3 steps.<\/p>\n<p>Delete all existing rules: \u201ciptables -F\u201d<br \/>\nAllow only incoming SSH: \u201ciptables -A INPUT -i eth0 -p tcp \u2013dport 22 -j ACCEPT\u201d<br \/>\nDrop all other incoming packets: \u201ciptables -A INPUT -j DROP\u201d<br \/>\nThe above works. But it is not complete. One problem with the above steps is that it doesn\u2019t restrict the outgoing packets.<\/p>\n<p>Default Chain Policy<\/p>\n<p>The default policy of a chain is ACCEPT. If you don\u2019t what what a chain means, you better read our iptables introduction article. So, both the INPUT and OUTPUT chain\u2019s default policy is ACCEPT. In the above 3 steps we dropped all incoming packets at the end (except incoming ssh). However, we didn\u2019t restrict the outgoing traffic.<\/p>\n<p>As you notice below, it says \u201c(policy ACCEPT)\u201d next to all the three chain names (INPUT, OUTPUT, and FORWARD). This indicates that the default chain policy is ACCEPT.<\/p>\n<p># iptables -L<br \/>\nChain INPUT (policy ACCEPT)<br \/>\ntarget     prot opt source               destination<br \/>\nACCEPT     tcp  &#8212;  anywhere             anywhere            tcp dpt:ssh<br \/>\nDROP       all  &#8212;  anywhere             anywhere            <\/p>\n<p>Chain FORWARD (policy ACCEPT)<br \/>\ntarget     prot opt source               destination         <\/p>\n<p>Chain OUTPUT (policy ACCEPT)<br \/>\ntarget     prot opt source               destination<br \/>\nSo, you have two options here.<\/p>\n<p>Option 1: Add drop rules<\/p>\n<p>At the end, add the following three drop rules that will drop all incoming, outgoing, and forward packets (except those that are defined above these three rules). If you do this, the default chain policy is still ACCEPT, which shouldn\u2019t matter, as you are dropping all the packets at the end anyway.<\/p>\n<p>iptables -A INPUT -j DROP<br \/>\niptables -A OUTPUT -j DROP<br \/>\niptables -A FORWARD -j DROP<br \/>\nOption 2: Change the default chain policy to DROP<\/p>\n<p>At the beginning, execute the following three commands that will change the chain\u2019s default policy to DROP.<\/p>\n<p>iptables -P INPUT DROP<br \/>\niptables -P OUTPUT DROP<br \/>\niptables -P FORWARD DROP<br \/>\nNow, if you add the allow ssh rule: \u201ciptables -A INPUT -i eth0 -p tcp \u2013dport 22 -j ACCEPT\u201d, and do iptables -L, you\u2019ll notice that it says \u201c(policy DROP)\u201d next to all the three chains.<\/p>\n<p># iptables -L<br \/>\nChain INPUT (policy DROP)<br \/>\ntarget     prot opt source               destination<br \/>\nACCEPT     tcp  &#8212;  anywhere             anywhere            tcp dpt:ssh<br \/>\nDROP       all  &#8212;  anywhere             anywhere            <\/p>\n<p>Chain FORWARD (policy DROP)<br \/>\ntarget     prot opt source               destination         <\/p>\n<p>Chain OUTPUT (policy DROP)<br \/>\ntarget     prot opt source               destination<br \/>\nBut there is a problem here. The allow ssh incoming connection rule will not work anymore, because all the outgoing packets are dropped.<\/p>\n<p>Allow Incoming Connections<\/p>\n<p>When the default policy is DROP for INPUT and OUTPUT chains, for every incoming firewall rule, you need to specify the following two rules.<\/p>\n<p>Request rule: This is the request that comes from the client to the server for the incoming connection.<br \/>\nResponse rule: This is for the response that goes out from the server to the client (for the corresponding incoming request).<br \/>\nExample 1: Allow incoming SSH connection<\/p>\n<p>This is to allow SSH connection from outside to your server. i.e You can ssh to your server from outside.<\/p>\n<p>This involves two steps. First, we need to allow incoming new SSH connections. Once the incoming ssh connection is allowed, we also need to allow the response back for that incoming ssh connection.<\/p>\n<p>First, Allow incoming SSH connection request, as shown below.<\/p>\n<p>iptables -A INPUT -i eth0 -p tcp &#8211;dport 22 -m state &#8211;state NEW,ESTABLISHED -j ACCEPT<br \/>\nIn the above example:<\/p>\n<p>iptables -A INPUT: Append the new rule to the INPUT chain. For incoming connection request, this always has to be INPUT.<br \/>\n-i eth0: This refers to the input interface. For incoming connections, this always has to be \u2018-i\u2019.<br \/>\n-p tcp: Indicates that this is for TCP protocol.<br \/>\n\u2013dport 22: This refers to the destination port for the incoming connection. Port 22 is for ssh.<br \/>\n-m state: This indicates that the \u201cstate\u201d matching module is used. We\u2019ll discuss more about \u201c-m\u201d option (and all available matching modules for iptables) in future article.<br \/>\n\u2013state NEW, ESTABLISHED: Options for the \u201cstate\u201d matching module. In this example, only NEW and ESTABLISHED states are allowed. The 1st time when a SSH connection request is initiated from the client to the server, NEW state is used. ESTABLISHED state is used for all further request from the client to the server.<br \/>\nNext, Allow outgoing (ESTABLISHED state only) SSH connection response (for the corresponding incoming SSH connection request).<\/p>\n<p>iptables -A OUTPUT -o eth0 -p tcp &#8211;sport 22 -m state &#8211;state ESTABLISHED -j ACCEPT<br \/>\nIn the above example:<\/p>\n<p>iptables -A OUTPUT: Append the new rule to the OUTPUT chain. Since this is for the response rule (for the corresponding incoming request) that goes out from the server, this should be OUTPUT.<br \/>\n-o eth0: This refers the output interface. For outgoing connections, this always has to be \u2018-o\u2019.<br \/>\n-p tcp: Indicates that this is for TCP protocol.<br \/>\n\u2013sport 22: This refers to the source port for the outgoing connection. Port 22 is for ssh. Since the incoming request (from the previous rule) came to the \u201cdestination\u201d port, the outgoing response will go through the \u201csource\u201d port.<br \/>\n-m state: This indicates that the \u201cstate\u201d matching module is used.<br \/>\n\u2013state ESTABLISHED: Since this is a response rule, we allow only ESTABLISHED connection (and not any NEW connection).<br \/>\nExample 2: Allow incoming HTTP connection<\/p>\n<p>This is to allow HTTP connection from outside to your server. i.e You can view your website running on the server from outside.<\/p>\n<p>Just like the above SSH incoming rules, this also involves two steps. First, we need to allow incoming new HTTP connection. Once the incoming HTTP connection is allowed, we need to allow the response back for that incoming HTTP connection.<\/p>\n<p>First, Allow incoming HTTP connection request, as shown below.<\/p>\n<p>iptables -A INPUT -i eth0 -p tcp &#8211;dport 80 -m state &#8211;state NEW,ESTABLISHED -j ACCEPT<br \/>\nNext, Allow outgoing (ESTABLISHED only) HTTP connection response (for the corrresponding incoming SSH connection request).<\/p>\n<p>iptables -A OUTPUT -o eth0 -p tcp &#8211;sport 80 -m state &#8211;state ESTABLISHED -j ACCEPT<br \/>\nNote: In the above HTTP request and response rule, everything is same as the SSH example except the port number.<\/p>\n<p>Allow Outgoing Connections<\/p>\n<p>When the default policy is DROP for the INPUT and OUTPUT chains, for every outgoing firewall rule, you need to specify the following two rules.<\/p>\n<p>Request rule: This is the request that goes out from the server to outside for the outgoing connection.<br \/>\nResponse rule: This is for the response that comes back from the outside to the server (for the corresponding outgoing request).<br \/>\nExample 3: Allow outgoing SSH connection<\/p>\n<p>This is to allow SSH connection from your server to the outside. i.e You can ssh to outside server from your server.<\/p>\n<p>This involves two steps. First, we need to allow outgoing new SSH connection. Once the outgoing ssh connection is allowed, we also need to allow the response back for that outgoing ssh connection.<\/p>\n<p>First, Allow outgoing SSH connection request, as shown below.<\/p>\n<p>iptables -A OUTPUT -o eth0 -p tcp &#8211;dport 22 -m state &#8211;state NEW,ESTABLISHED -j ACCEPT<br \/>\nIn the above example:<\/p>\n<p>iptables -A OUTPUT: Append the new rule to the OUTPUT chain. For outgoing connection request, this always has to be OUTPUT.<br \/>\n-o eth0: This refers the output interface. For outgoing connections, this always has to be \u2018-o\u2019.<br \/>\n-p tcp: Indicates that this is for TCP protocol.<br \/>\n\u2013dport 22: This refers to the destination port for the outgoing connection.<br \/>\n-m state: This indicates that \u201cstate\u201d matching module is used.<br \/>\n\u2013state NEW, ESTABLISHED: Options for the \u201cstate\u201d matching module. In this example, only NEW and ESTABLISHED states are allowed. The 1st time when a SSH connection request is initiated from the server to the outside, NEW state is used. ESTABLISHED state is used for all further request from the server to the outside.<br \/>\nNext, Allow outgoing (ESTABLISHED only) SSH connection response (for the corresponding incoming SSH connection request).<\/p>\n<p>iptables -A INPUT -i eth0 -p tcp &#8211;sport 22 -m state &#8211;state ESTABLISHED -j ACCEPT<br \/>\nIn the above example:<\/p>\n<p>iptables -A INPUT: Append the new rule to the INPUT chain. Since this is for the response rule (for the corresponding outgoing request) that comes from the outside to the server, this should be INPUT.<br \/>\n-i eth0: This refers the input interface. For incoming connections, this always has to be \u2018-i\u2019.<br \/>\n-p tcp: Indicates that this is for TCP protocol.<br \/>\n\u2013sport 22: This refers to the source port for the incoming connection. Since the outgoing request (from the previous rule) went to the \u201cdestination\u201d port, the incoming response will come from the \u201csource\u201d port.<br \/>\n-m state: This indicates that the \u201cstate\u201d matching module is used.<br \/>\n\u2013state ESTABLISHED: Since this is a response rule, we allow only ESTABLISHED connection (and not any NEW connection).<br \/>\nPutting it all together<\/p>\n<p>Create rules.sh shell script which does the following:<\/p>\n<p>Delete all existing rules<br \/>\nSet default chain policies<br \/>\nAllow inbound SSH<br \/>\nAllow inbound HTTP<br \/>\nAllow outbound SSH<br \/>\nFirst, create the rules.sh<\/p>\n<p>$ vi rules.sh<br \/>\n# 1. Delete all existing rules<br \/>\niptables -F<\/p>\n<p># 2. Set default chain policies<br \/>\niptables -P INPUT DROP<br \/>\niptables -P FORWARD DROP<br \/>\niptables -P OUTPUT DROP<\/p>\n<p># 3. Allow incoming SSH<br \/>\niptables -A INPUT -i eth0 -p tcp &#8211;dport 22 -m state &#8211;state NEW,ESTABLISHED -j ACCEPT<br \/>\niptables -A OUTPUT -o eth0 -p tcp &#8211;sport 22 -m state &#8211;state ESTABLISHED -j ACCEPT<\/p>\n<p># 4. Allow incoming HTTP<br \/>\niptables -A INPUT -i eth0 -p tcp &#8211;dport 80 -m state &#8211;state NEW,ESTABLISHED -j ACCEPT<br \/>\niptables -A OUTPUT -o eth0 -p tcp &#8211;sport 80 -m state &#8211;state ESTABLISHED -j ACCEPT<\/p>\n<p># 5. Allow outgoing SSH<br \/>\niptables -A OUTPUT -o eth0 -p tcp &#8211;dport 22 -m state &#8211;state NEW,ESTABLISHED -j ACCEPT<br \/>\niptables -A INPUT -i eth0 -p tcp &#8211;sport 22 -m state &#8211;state ESTABLISHED -j ACCEPT<br \/>\nNext, execute the rules.sh and view the rules.<\/p>\n<p># chmod u+x rules.sh<\/p>\n<p># .\/rules.sh<\/p>\n<p># iptables -L<br \/>\nChain INPUT (policy DROP)<br \/>\ntarget     prot opt source      destination<br \/>\nACCEPT     tcp  &#8212;  anywhere    anywhere      tcp dpt:ssh state NEW,ESTABLISHED<br \/>\nACCEPT     tcp  &#8212;  anywhere    anywhere      tcp dpt:http state NEW,ESTABLISHED<br \/>\nACCEPT     tcp  &#8212;  anywhere    anywhere      tcp spt:ssh state ESTABLISHED <\/p>\n<p>Chain FORWARD (policy DROP)<br \/>\ntarget     prot opt source      destination         <\/p>\n<p>Chain OUTPUT (policy DROP)<br \/>\ntarget     prot opt source      destination<br \/>\nACCEPT     tcp  &#8212;  anywhere    anywhere      tcp spt:ssh state ESTABLISHED<br \/>\nACCEPT     tcp  &#8212;  anywhere    anywhere      tcp spt:http state ESTABLISHED<br \/>\nACCEPT     tcp  &#8212;  anywhere    anywhere      tcp dpt:ssh state NEW,ESTABLISHED<br \/>\nUsing this as a basis you should be able to write your own incoming and outgoing iptables firewall rules. There is lot more to cover in IPTables. Stay tuned!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Configurando o Iptables e Fazendo Regras B\u00e1sicas 20 de janeiro de 2004 Postado por: Thadeu Camargo J\u00e1 est\u00e1 mais do que comprovado: Hoje em dia uma m\u00e1quina sem conex\u00e3o com a internet n\u00e3o tem maior valia do que uma m\u00e1quina de escrever. \u00c9 certo que&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[2],"tags":[],"_links":{"self":[{"href":"https:\/\/blog.abratel.com.br\/index.php?rest_route=\/wp\/v2\/posts\/510"}],"collection":[{"href":"https:\/\/blog.abratel.com.br\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.abratel.com.br\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.abratel.com.br\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.abratel.com.br\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=510"}],"version-history":[{"count":0,"href":"https:\/\/blog.abratel.com.br\/index.php?rest_route=\/wp\/v2\/posts\/510\/revisions"}],"wp:attachment":[{"href":"https:\/\/blog.abratel.com.br\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=510"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.abratel.com.br\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=510"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.abratel.com.br\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=510"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}