Duvida Iptables [RESOLVIDO]

1. Duvida Iptables [RESOLVIDO]

Marcos Matuzalem Alvarez Rodrigues
marcos1983

(usa Debian)

Enviado em 14/08/2011 - 19:22h

Senhores,

Criei o firewall abaixo, porém quando executo o script eu perco o acesso ao SSH da máquina pela rede internet e a internet também não funciona mais para nenhum cliente da rede.

Outro problema que tive é que necessito com o MASQUERADE conseguir criar regras de quais protocolos podem trafegar porque a minha internet é com IP DINAMICO, tentei criar regras como os 2 exemplos abaixo e não obtive sucesso. Alguem tem alguma sugestão do que preciso incluir/excluir/alterar nesse script para que ele funcione?

Exemplos:
iptables -t nat -A POSTROUTING -s 192.168.15.1/24 -d 0/0 -p tcp --dport 110 -j MASQUERADE
iptables -t nat -A POSTROUTING -s 192.168.15.1/24 -d 0/0 -p tcp --dport 80 -j MASQUERADE

O mesmo equipamento é firewall e também webserver. Possui duas placas de rede sendo a eth0 = placa interna e eth1 = placa externa (internet)

######################
SCRIPT FIREWALL
######################

#/bin/bash

fire_start(){
iptables -P INPUT DROP
iptables -P OUTPUT DROP

#--------------------------------------------------#
# Regras de INPUT #
#--------------------------------------------------#
echo "Definindo regras de INPUT"

###################################################
# Compartilhamento da Internet #
###################################################
iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
echo "1" > /proc/sys/net/ipv4/ip_forward

#####################################################
# Aceita todo trafego loopback #
#####################################################
iptables -A INPUT -i lo -j ACCEPT

#####################################################
# Libera trafego LAN #
#####################################################
iptables -A INPUT -s 192.168.15.0/24 -i eth0 -j ACCEPT

#####################################################
# Redirecionamento Terminal Service Desktop Quarto #
#####################################################
iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 3389 -j DNAT --to-destination 192.168.15.31:3389

#####################################################
# Redirecionamento Terminal Service Notebook Marcos #
#####################################################
iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 3390 -j DNAT --to-destination 192.168.15.30:3390

#####################################################
# Redirecionamento Local WebServer #
#####################################################
iptables -v -A INPUT -p tcp --dport 8181 -j ACCEPT

#####################################################
# Redirecionamento WebServer BKP #
#####################################################
iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 8082 -j DNAT --to-destination 192.168.15.110:8082

}

fire_stop(){
echo "Parando o Firewall"
iptables -F
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT
}

fire_restart(){
fire_stop
sleep 1
fire_start
}

case "$1" in
'start')
fire_start
;;
'stop')
fire_stop
;;
'restart')
fire_restart
;;
*)
echo "usage $0 start|stop|restart"
esac




  


2. Re: Duvida Iptables [RESOLVIDO]

Perfil removido
removido

(usa Nenhuma)

Enviado em 14/08/2011 - 21:00h

amigão...

o problema que está impedindo voce de acessar a internet ou outro computador da rede é as regras descritas abaixo que estão no seu script de firewall:

iptables -P INPUT DROP
iptables -P OUTPUT DROP

OBS: estas duas regras estão bloqueando tudo que sai e entra na sua rede.

SOLUÇÃO: exclua estas duas regras e veja se consegue acessar a internet e acessar via ssh


3. Duvida Iptables (resposta)

Marcos Matuzalem Alvarez Rodrigues
marcos1983

(usa Debian)

Enviado em 14/08/2011 - 22:35h

Amigo.. Valeu pelo retorno..
Então ....
Eu estou criando o firewall com o intuito de bloquear tudo e somente liberar na minha interface de rede que recebe o link da internet, o meu webserver(apache2) que esta na porta 8082, conexão SSH e alguns redirects para o TS internamente. Como no meu webserver tenho uma pagina em PHP com banco de dados estou preocupado com a questão de segurança, pois eu sei que não é recomendado ter tudo isso em um único equipamento, mas na minha situação atual não tenho como investir em outro equipamento.
Se eu remover essas regras, consigo sem nenhum problema acessar o meu ssh, o meu webserver, porém estou vulnerável na internet e é isso que queria fechar.
Eu estou com uma apostila de iptables e ja apliquei varias formas, mas não obtive sucesso em nenhuma delas por isso procurei pelo site. Você pode me dar um auxilio?
Valeu amigo !!!


4. Re: Duvida Iptables [RESOLVIDO]

Perfil removido
removido

(usa Nenhuma)

Enviado em 14/08/2011 - 22:43h

por nada..
Bom amigo...

1º - O que deseja realmente fazer, pois ainda não ficou muito claro pra mim?

2º - deseja bloquear acesso externo e interno também ou só externo.

3º - deseja permitir acesso de qual maquina interna e bloquear para quais maquinas, só internet?

4º - deseja acessar seu ssh e o seu webserver internamente ou externamente?

esclarece ai, para continuar dando suporte a voce...


5. Duvida Iptables (resposta2)

Marcos Matuzalem Alvarez Rodrigues
marcos1983

(usa Debian)

Enviado em 14/08/2011 - 22:56h

1)
Preciso que o meu servidor fique com as portas 8081 (apache2) e SSH (22) liberadas para acesso externo pela interface de rede, além disso preciso redirecionar a porta 3389 para outro equipamento internamente. a rede interna pode ficar tudo liberado.
Tudo isso eu ja fiz e deu certo, mas quando coloco as regras de "DROP" para deixar tudo bloqueado e somente deixar isso liberado, não consigo mais nem acessar o meu SSH.

2)
No acesso externo somente as portas 8082 (apache) e 22 do SSH.

3)
Internamente pode deixar tudo liberado.. sem problemas...

4)
Externamente.

Observação: Além de firewall a maquina também compartilha internet com a seguinte regra
iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE

Valeuu !!!


6. Re: Duvida Iptables [RESOLVIDO]

Perfil removido
removido

(usa Nenhuma)

Enviado em 14/08/2011 - 23:08h

blz... valeu pelos esclarecimentos....

pode sim tirar, você tem que entender que o iptables executa uma regra por vez, ou seja uma linha por vez.

então se colocar no seu script: iptables -P INPUT DROP; iptables -P OUTPUT DROP( ESSA REGRA SERÁ EXECUTADA E BLOQUEARA TODO ACESSO DE ENTRADA E SAIDA NO HOST).

SE TIRÁ ESSAS REGRAS NÃO TERÁ PROBLEMAS AO SEU SSH NEM WEBSERVER.

PORÉM RECOMENDO QUE COLOQUE REGRAS QUE PROIBAM ACESSO DE HOSTS INDESEJADOS.

por exemplo: iptables -A INPUT -i eth0 -m multiport -p tcp --dport 22,3389,8081 -j ACCEPT # aceita no host conexões de entrada pela interface eth0 direcionadas as portas 22,3389 e 8081 usando o protocolo tcp.
iptables -A INPUT -p tcp --syn -j DROP # bloqueia novas conexões.

PERGUNTA: SEU WEBSERVER E SERVIDOR SSH ESTÁ ATRÁS DO SERVIDOR DE FIREWALL?


7. Duvida Iptables (resposta3)

Marcos Matuzalem Alvarez Rodrigues
marcos1983

(usa Debian)

Enviado em 14/08/2011 - 23:21h

Então amigo...
Como que eu faço para deixar esses acessos liberados (apache + ssh) na minha interface de internet e bloquear todos os outros acessos que poderia ter em meu servidor? Como te disse, minha preocupação é saber se o meu servidor esta totalmente seguro e para isso quero aplicar as regras da maneira mais segura possível. Um exemplo disso, tenho o mysql que utiliza a porta 3306... queria ter certeza que ninguem acessaria, sem contar as outras portas que desconheço..
Eu li na internet que existe uma forma de bloquear tudo e somente deixar liberado o que eu preciso....
O meu webserver e servidor SSH estão todos no mesmo equipamento... (apache2 + SSHD)...


8. Re: Duvida Iptables [RESOLVIDO]

Perfil removido
removido

(usa Nenhuma)

Enviado em 14/08/2011 - 23:31h

bom vamos lá...

1º - quando se abre uma porta já deixa brechas, então não vai ser totalmente seguro.

2º - Há sim formas de abrir estas portas e bloquear as outras.

vamos ver como fazer isso:

#### Bloqueando todas as portas exceto 8082, 22, 3389 ###

iptables -A INPUT -i eth1 -m multiport -p tcp --dport 22,3389,8082 -j ACCEPT # aceita no host conexões de entrada pela interface eth1 direcionadas as portas 22,3389 e 8082 usando o protocolo tcp.

iptables -A INPUT -p tcp --syn -j DROP # bloqueia novas conexões externas.

echo 1 > /proc/sys/net/ipv4/tcp_syncookies # protege contra ataques syn_flood

seu script final ficaria assim:

######################
SCRIPT FIREWALL
######################

#/bin/bash

fire_start(){


#--------------------------------------------------#
# Regras de INPUT #
#--------------------------------------------------#
echo "Definindo regras de INPUT"

iptables -A INPUT -i eth1 -m multiport -p tcp --dport 22,3389,8082 -j ACCEPT # aceita no host conexões de entrada pela interface eth1 direcionadas as portas 22,3389 e 8082 usando o protocolo tcp.

iptables -A INPUT -p tcp --syn -j DROP # bloqueia novas conexões externas.

echo 1 > /proc/sys/net/ipv4/tcp_syncookies # protege contra ataques syn_flood

###################################################
# Compartilhamento da Internet #
###################################################
iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
echo "1" > /proc/sys/net/ipv4/ip_forward

#####################################################
# Aceita todo trafego loopback #
#####################################################
iptables -A INPUT -i lo -j ACCEPT

#####################################################
# Libera trafego LAN #
#####################################################
iptables -A INPUT -s 192.168.15.0/24 -i eth0 -j ACCEPT

#####################################################
# Redirecionamento Terminal Service Desktop Quarto #
#####################################################
iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 3389 -j DNAT --to-destination 192.168.15.31:3389

#####################################################
# Redirecionamento Terminal Service Notebook Marcos #
#####################################################
iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 3390 -j DNAT --to-destination 192.168.15.30:3390

#####################################################
# Redirecionamento Local WebServer #
#####################################################
iptables -v -A INPUT -p tcp --dport 8181 -j ACCEPT

#####################################################
# Redirecionamento WebServer BKP #
#####################################################
iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 8082 -j DNAT --to-destination 192.168.15.110:8082

}

fire_stop(){
echo "Parando o Firewall"
iptables -F
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT
}

fire_restart(){
fire_stop
sleep 1
fire_start
}

case "$1" in
'start')
fire_start
;;
'stop')
fire_stop
;;
'restart')
fire_restart
;;
*)
echo "usage $0 start|stop|restart"
esac

OBS: essas regras acima irão abrir as portas descritas e bloquear as outras.

Resolvido ou não?


9. Re: Duvida Iptables [RESOLVIDO]

Perfil removido
removido

(usa Nenhuma)

Enviado em 15/08/2011 - 19:10h

Fala amigo, blz?

amigo a solução deu certo? esperei sua postagem mas até agora nada.

Logo abaixo deixo mais uma dica segurança para seu script:

iptables -A FORWARD -p tcp --syn -m limit --limit 10/s -j ACCEPT # impede que seu servidor sofra uma ataque que para com a resposta da sua rede.

iptables -A INPUT -i eth1 -m multiport -p tcp --dport 22,3389,8082 -j ACCEPT # aceita no host conexões de entrada pela interface eth1 direcionadas as portas 22,3389 e 8082 usando o protocolo tcp.

iptables -A INPUT -p tcp --syn -j DROP # bloqueia novas conexões externas.

echo 1 > /proc/sys/net/ipv4/tcp_syncookies # protege contra ataques syn_flood

OBS: coloque essas regras no inicio do script.

abraços, posta ai o resultado final.



10. Duvida Iptables (resposta4)

Marcos Matuzalem Alvarez Rodrigues
marcos1983

(usa Debian)

Enviado em 15/08/2011 - 20:24h

Amigoo....

Tudo indica que deu tudo certo, muito obrigado pelo HELP.
Não conhecia a regra "iptables -A INPUT -p tcp --syn -j DROP" onde ela bloqueia todo o restante do acesso externo após as regras de liberação.... Acredito que meu server esteja seguro, agora pretendo aplicar regras de segurança de configuração no SSH e APACHE e acredito que com isso meu server esteja o máximo seguro possível. Se você tiver qualquer dica para acrescentar, ela é bem vinda !! rrss......

Nas minhas pesquisas ai pela NET encontrei essas regras abaixo que dizem aprimorar a segurança do meu server, você acha que se eu aplicá-las vou ter algum problema ou se realmente vou estar mais seguro?

Observação: Atualmente essas regras não estão aplicadas....

#####################################################
# Derruba qualquer conexao desconhecida #
#####################################################
#iptables -A INPUT -j LOG --log-prefix "FIREWALL: INPUT "
#iptables -A INPUT -j DROP

#####################################################
# Protecao contra IP Spoofing #
#####################################################
#for i in /proc/sys/net/ipv4/conf/*/rp_filter;
#do echo 1 >$i done

#####################################################
# Protecao contra worms #
#####################################################
#iptables -A FORWARD -p tcp --dport 135 -i eth1 -j REJECT

#####################################################
# Protecao contra trojans #
#####################################################
#iptables -N TROJAN
#iptables -A TROJAN -j DROP
#iptables -A INPUT -p TCP -i eth1 --dport 666 -j TROJAN
#iptables -A INPUT -p TCP -i eth1 --dport 666 -j TROJAN
#iptables -A INPUT -p TCP -i eth1 --dport 4000 -j TROJAN
#iptables -A INPUT -p TCP -i eth1 --dport 6000 -j TROJAN
#iptables -A INPUT -p TCP -i eth1 --dport 6006 -j TROJAN
#iptables -A INPUT -p TCP -i eth1 --dport 16660 -j TROJAN

#####################################################
# Protecao contra trinoo #
#####################################################
#iptables -N TRINOO
#iptables -A TRINOO -j DROP
#iptables -A INPUT -p TCP -i eth1 --dport 27444 -j TRINOO
#iptables -A INPUT -p TCP -i eth1 --dport 27665 -j TRINOO
#iptables -A INPUT -p TCP -i eth1 --dport 31335 -j TRINOO
#iptables -A INPUT -p TCP -i eth1 --dport 34555 -j TRINOO
#iptables -A INPUT -p TCP -i eth1 --dport 35555 -j TRINOO

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

#####################################################
# Protecao contra Back Orifice #
#####################################################
#iptables -A INPUT -p tcp --dport 31337 -j DROP
#iptables -A INPUT -p udp --dport 31337 -j DROP

#####################################################
# Protecao contra NETBUS #
#####################################################
#iptables -A INPUT -p tcp --dport 12345:12346 -j DROP
#iptables -A INPUT -p udp --dport 12345:12346 -j DROP

#####################################################
# Bloqueia ping em excesso #
#####################################################
#iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT
#iptables -A INPUT -p icmp --icmp-type echo-request -j DROP
#iptables -A INPUT -j DROP

####################################################
# Anti-Redirects #
####################################################
#echo 0 > /proc/sys/net/ipv4/conf/all/accept_redirects

####################################################
# Anti Source Route #
####################################################
#echo 0 > /proc/sys/net/ipv4/conf/all/accept_source_route

####################################################
# Ignore echo broadcasts #
####################################################
echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts

####################################################
# Anti-Bugus Response #
####################################################
#echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses



11. resposta...

Perfil removido
removido

(usa Nenhuma)

Enviado em 15/08/2011 - 22:22h

amigo, coloquei um script com todas essas regras no script, veja abaixo como ficou:

OBS: Antes de tudo faça um backup do script original e teste esse novo. veja se dá certo. se dê certo ótimo substitua se não dá certo coloque o original atual, posta aqui o resultado.

######################
# SCRIPT FIREWALL #
######################

#/bin/bash

fire_start(){

#--------------------------------------------------#
# Regras de INPUT #
#--------------------------------------------------#
echo "Definindo regras de INPUT"

###################################################
# Compartilhamento da Internet #
###################################################
iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
echo "1" > /proc/sys/net/ipv4/ip_forward

##################################################
# protege contra ataques syn_flood #
##################################################
echo 1 > /proc/sys/net/ipv4/tcp_syncookies

################################################################################
# impede que seu servidor sofra uma ataque que para com a resposta da sua rede.#
################################################################################
iptables -A FORWARD -p tcp --syn -m limit --limit 10/s -j ACCEPT

#######################################################################################################################
# aceita no host conexões de entrada pela interface eth1 direcionadas as portas 22,3389 e 8082 usando o protocolo tcp.#
#######################################################################################################################
iptables -A INPUT -i eth1 -m multiport -p tcp --dport 22,3389,8082 -j ACCEPT

######################################################################################################################
# bloqueia tentativas de novas conexões ( tentativas de aberturas de conexões ) #
# descarta pacotes mal formados, protegendo contra ataques diversos #
######################################################################################################################
iptables -A INPUT -p tcp --syn -j DROP
iptables -A INPUT -i eth1 -m state --state INVALID -j DROP

#####################################################
# Protecao contra IP Spoofing #
#####################################################
for i in /proc/sys/net/ipv4/conf/*/rp_filter;
do echo 1 >$i done

#####################################################
# Ignora os pings #
#####################################################
iptables -A INPUT -p icmp --icmp-type echo-request -j DROP

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

#####################################################
# Protecao contra worms #
#####################################################
#iptables -A FORWARD -p tcp --dport 135 -i eth1 -j REJECT

#####################################################
# Aceita todo trafego loopback #
#####################################################
iptables -A INPUT -i lo -j ACCEPT

#####################################################
# Libera trafego LAN #
#####################################################
iptables -A INPUT -s 192.168.15.0/24 -i eth0 -j ACCEPT

#####################################################
# Redirecionamento Terminal Service Desktop Quarto #
#####################################################
iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 3389 -j DNAT --to-destination 192.168.15.31:3389

#####################################################
# Redirecionamento Terminal Service Notebook Marcos #
#####################################################
iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 3390 -j DNAT --to-destination 192.168.15.30:3390

#####################################################
# Redirecionamento Local WebServer #
#####################################################
iptables -v -A INPUT -p tcp --dport 8181 -j ACCEPT

#####################################################
# Redirecionamento WebServer BKP #
#####################################################
iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 8082 -j DNAT --to-destination 192.168.15.110:8082

######################################################################################################################
# Bloqueia todo trafego de entrada pela interface eth1 (independente do protocolo e porta usada para abertua da mesma#
######################################################################################################################
#iptables -A INPUT -j LOG --log-prefix "FIREWALL: INPUT " ( está regra não sei do que se trata, por isso deixei comentada)

iptables -A INPUT -i eth1 -j DROP

####################################################
# Anti-Redirects #
####################################################
echo 0 > /proc/sys/net/ipv4/conf/all/accept_redirects

####################################################
# Anti Source Route #
####################################################
echo 0 > /proc/sys/net/ipv4/conf/all/accept_source_route

####################################################
# Ignore echo broadcasts #
####################################################
echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts

####################################################
# Anti-Bugus Response #
####################################################
echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses

}

fire_stop(){
echo "Parando o Firewall"
iptables -F
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT
}

fire_restart(){
fire_stop
sleep 1
fire_start
}

case "$1" in
'start')
fire_start
;;
'stop')
fire_stop
;;
'restart')
fire_restart
;;
*)
echo "usage $0 start|stop|restart"
esac


12. Duvida Iptables (resposta5)

Marcos Matuzalem Alvarez Rodrigues
marcos1983

(usa Debian)

Enviado em 15/08/2011 - 23:07h

Amigo...

Eu somente queria esclarecer algumas regras....

A regra abaixo libera os acessos nas respectivas portas
#######################################################################################################################
# aceita no host conexõde entrada pela interface eth1 direcionadas as portas 22,3389 e 8082 usando o protocolo tcp.# #######################################################################################################################
iptables -A INPUT -i eth1 -m multiport -p tcp --dport 22,3389,8082 -j ACCEPT


Nessas 2 regras elas fazem o redirecionamento para o host.
#####################################################
# Redirecionamento Terminal Service Desktop Quarto # #####################################################
iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 3389 -j DNAT --to-destination 192.168.15.31:3389
#####################################################
# Redirecionamento WebServer BKP #
#####################################################
iptables -t nat -A PREROUTING -p tcp -i eth1 --dport 8082 -j DNAT --to-destination 192.168.15.110:8082

Realmente é necessário ter todas essas regras ou somente deveria ter as que fazer o PREROUTING?



Você inseriu esse drop no final das regras de iptable, ele não vai bloquear as liberações feitas nas linhas acima? Depois que rodei o script minha pagina parou de abrir... hehehehehe


######################################################################################################################
# Bloqueia todo trafego de entrada pela interface eth1 (independente do protocolo e porta usada para abertua da mesma# ######################################################################################################################
#iptables -A INPUT -j LOG --log-prefix "FIREWALL: INPUT " ( estáegra nãsei do que se trata, por isso deixei comentada)

iptables -A INPUT -i eth1 -j DROP



valeu MAN !!!



01 02



Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts