Firewall avançado
Publicado por Eduardo Vieira Mendes 21/07/2008
[ Hits: 9.065 ]
Script de firewall avançado, com várias opções, como liberação de certos ips, liberação de ip/porta, checagem de sanidade do script, compatibilidade com funções start|stop|restart do RedHat, entre outros. Tudo bem comentado.
#!/bin/sh # iptables, by Alexandre Iamamoto # $Id: iptables,v 1.61 06/06/2004 10:03:00 # chkconfig: 2345 08 80 # description: Script de configuraçao da rede e firewall # processname: iptables # Usando RedHat Linux? REDHAT="YES" # O firewall está ativado (Y/N)? ATIVADO="Y" ATIVAREDIR="Y" ATIVAPROXY="Y" # Executar teste de Sanidade do script? OVERRIDE_SANITY_CHECKS="FALSE" PROXY="192.168.0.254" # Endereco do Proxy PROXYPORTA="3128" # Porta do Proxy REDIRECIONAMENTOS=/etc/redirecionamentos.txt PORTAS_LIBERADAS_TCP=(20 21 22 25 53 80 110 1234 143 1064 1065 1723 3389) PORTAS_LIBERADAS_UDP=(1234 1723 53 5222) # Cores VERDE=$'\e[32;01m' AMARELO=$'\e[33;01m' VERMELHO=$'\e[31;01m' NORMAL=$'\e[0m' # Interfaces de Rede # Modifique suas interfaces de rede aqui # Interna e externa INTERNALIF="eth0" EXTERNALIF="eth1" # Enderecos de Rede # Rede interna INTERNALNET="192.168.0.0/24" # Broadcast INTERNALBCAST="192.168.0.255" # Especificos # Ips que sao permitidos tudo, nao passam pelo proxy IPSPERMITIDOSTUDO=(192.168.0.1 192.168.0.2 192.168.0.3 192.168.0.9 192.168.0.10 192.168.0.74 192.168.0.65 192.168.0.54 192.168.0.53 192.168.0.94 192.168.0.55 192.168.0.92 192.168.0.82 192.168.0.95 192.168.0.77 192.198.0.66); MODULOSA=(ip_tables iptable_filter ip_conntrack ip_conntrack_ftp ip_nat_ftp); # Mude os x para os seus ips, externo e interno EXTERNAL_IP=xxx.xxx.xxx.xx INTERNAL_IP=xxx.xxx.x.xxx OVERRIDE_NO_FORWARD="FALSE" USE_SYNCOOKIES="TRUE" # Caminhos de programas DMESG="/bin/dmesg" IPTABLES="`which iptables`" MODPROBE="/sbin/modprobe" /sbin/modprobe ip_tables /sbin/modprobe iptable_filter /sbin/modprobe ip_conntrack /sbin/modprobe ip_conntrack_ftp /sbin/modprobe ip_nat_ftp # Este é uma função do Red Hat que habilita o sistema de start/stop/restart if [ X"$REDHAT" = X"YES" ]; then . /etc/rc.d/init.d/functions case "$1" in stop) action "Desligando Firewall:" echo echo -n "Limpando regras: " ${IPTABLES} -t filter -F INPUT echo -n "INPUT " ${IPTABLES} -t filter -F OUTPUT echo -n "OUTPUT1 " ${IPTABLES} -t filter -F FORWARD echo -n "FORWARD " ${IPTABLES} -t nat -F PREROUTING echo -n "PREROUTING1 " ${IPTABLES} -t nat -F OUTPUT echo -n "OUTPUT2 " ${IPTABLES} -t nat -F POSTROUTING echo -n "POSTROUTING " ${IPTABLES} -t mangle -F PREROUTING echo -n "PREROUTING2 " ${IPTABLES} -t mangle -F OUTPUT echo -n "OUTPUT3" echo exit 0 ;; status) echo "The status command is not supported for iptables" exit 0 ;; restart|reload) $0 stop exec $0 start ;; start) action "Iniciando Firewall:" echo ;; *) echo "Utilizacao: iptables (start|stop|restart)" exit 1 esac fi ################################################################ #------------------------------------------------------------ #Informa configuracoes echo Interface externa: $EXTERNALIF Ip externo: $EXTERNAL_IP echo Interface interna: $INTERNALIF Ip externo: $INTERNAL_IP #Inicia teste de sanidade no script if [ "$OVERRIDE_SANITY_CHECKS" = "TRUE" ] ; then echo "Teste Ignorado! Se acontecerem problemas não reclame!" echo "Se existe um motivo para isso por favor informe o suporte do sistema 62 205-1422" echo echo -n "Aguarde 5 segundos..." sleep 5 echo "continuando" echo echo else # Esta ativado? if ! [ "$ATIVADO" = "Y" ] ; then echo echo "${VERMELHO} SUA CONFIGURACAO INDICA QUE O FIREWALL ESTA DESATIVADO" echo -n "$VERDE" exit 99 fi # É dificil executar o firewall sem o iptables... if ! [ -x $IPTABLES ] ; then echo echo "ERRO NA CONFIGURAÇÃO: ${IPTABLES} não existe ou não é executável!" exit 4 fi fi # Insere os modulos no kernel dmesg -n 1 #Mata mensagem de carregamento let CONTADOR=0; for TEMP_VAR01 in ${MODULOSA[@]} ; do echo Carregando o modulo de kernel: $TEMP_VAR01 $MODPROBE $TEMP_VAR01 let CONTADOR=$CONTADOR+1; done; echo -n "Limpando regras: " ${IPTABLES} -t filter -F INPUT echo -n "INPUT " ${IPTABLES} -t filter -F OUTPUT echo -n "OUTPUT1 " ${IPTABLES} -t filter -F FORWARD echo -n "FORWARD " ${IPTABLES} -t nat -F PREROUTING echo -n "PREROUTING1 " ${IPTABLES} -t nat -F OUTPUT echo -n "OUTPUT2 " ${IPTABLES} -t nat -F POSTROUTING echo -n "POSTROUTING " ${IPTABLES} -t mangle -F PREROUTING echo -n "PREROUTING2 " ${IPTABLES} -t mangle -F OUTPUT echo -n "OUTPUT3" echo ##Setup sysctl controls which affect tcp/ip # if [ "$INTERNALNET" != "" ] && [ "$OVERRIDE_NO_FORWARD" != "TRUE" ] ; then echo -n "Checando por IP Forwarding..." if [ -e /proc/sys/net/ipv4/ip_forward ] ; then echo 1 > /proc/sys/net/ipv4/ip_forward echo "ativado." else echo "support not found! This will cause problems if you need to do any routing." fi fi # Enable TCP Syncookies echo -n "Checando por IP SynCookies..." if [ -e /proc/sys/net/ipv4/tcp_syncookies ] ; then if [ "$USE_SYNCOOKIES" = "TRUE" ] ; then echo 1 > /proc/sys/net/ipv4/tcp_syncookies echo "ativado." else echo 0 > /proc/sys/net/ipv4/tcp_syncookies echo "desativado." fi else echo "suporte nao encontrado, porem ok." fi #Disabling IP Spoofing attacks. echo 2 > /proc/sys/net/ipv4/conf/all/rp_filter #Don't respond to broadcast pings echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts #Defragment all Packets #Default now #Enable forwarding #echo 1 >/proc/sys/net/ipv4/ip_forward #Block source routing echo 0 >/proc/sys/net/ipv4/conf/all/accept_source_route #Kill timestamps. These have been the subject of a recent bugtraq thread echo 0 > /proc/sys/net/ipv4/tcp_timestamps #Enable SYN Cookies #echo 1 > /proc/sys/net/ipv4/tcp_syncookies #Kill redirects echo 0 >/proc/sys/net/ipv4/conf/all/accept_redirects #Enable bad error message protection echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses #Allow dynamic ip addresses echo "1" > /proc/sys/net/ipv4/ip_dynaddr #Log martians (packets with impossible addresses) #RiVaL said that certain NICs don't like this. Comment out if necessary. #echo 1 >/proc/sys/net/ipv4/conf/all/log_martians echo 0 >/proc/sys/net/ipv4/conf/all/log_martians #Set out local port range echo "32768 61000" >/proc/sys/net/ipv4/ip_local_port_range #Reduce DoS'ing ability by reducing timeouts echo 30 > /proc/sys/net/ipv4/tcp_fin_timeout echo 1800 > /proc/sys/net/ipv4/tcp_keepalive_time echo 1 > /proc/sys/net/ipv4/tcp_window_scaling echo 0 > /proc/sys/net/ipv4/tcp_sack echo 1280 > /proc/sys/net/ipv4/tcp_max_syn_backlog # # Permite que pacotes oriundos da interface loopback # $IPTABLES -A INPUT -i lo -j ACCEPT # # Mata qualquer pacote venha da rede 127 # $IPTABLES -A INPUT -d 127.0.0.0/8 -j REJECT # # Permite acesso ao servidor via redes locais e VPN # $IPTABLES -A INPUT -i $INTERNALIF -s $INTERNALNET -j ACCEPT # # Funcao navegacao total dos ips listados na variavel # echo Ips Liberados a sair totalmente: ${IPSPERMITIDOSTUDO} let CONTADOR=0; for TEMP_VAR01 in ${IPSPERMITIDOSTUDO[@]} ; do echo Liberando acesso completo a: $TEMP_VAR01 $IPTABLES -A FORWARD -o $EXTERNALIF -i $INTERNALIF -s $TEMP_VAR01 -j ACCEPT; let CONTADOR=$CONTADOR+1; done; # #Allow IPV6 tunnel traffic #$IPTABLES -A INPUT -p ipv6 -j ACCEPT #Allow IPSEC tunnel traffic #$IPTABLES -A INPUT -p 50 -j ACCEPT #Allow all traffic from the ipsec device to the internal network #$IPTABLES -A FORWARD -i ipsec0 -o $INTERNALIF -j ACCEPT #Kill anything from outside claiming to be from internal network $IPTABLES -A INPUT -i $EXTERNALIF -s $INTERNALNET -j REJECT ##ICMP #ping don't forward pings going inside #$IPTABLES -A FORWARD -p icmp --icmp-type echo-request -o $INTERNALIF -j REJECT #ping flood protection $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 #Deny icmp to broadcast address $IPTABLES -A INPUT -p icmp -d $INTERNALBCAST -j DROP #Allow all other icmp $IPTABLES -A INPUT -p icmp -j ACCEPT #Proteçao contra tcp FIN ##Allow established connections #Unlike ipchains, we don't have to go through the business of allowing #a local port range- just allow all connections already established. $IPTABLES -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT #Note that unlike ipchains, the following must be enabled even with masquerading #Don't forward SMB related traffic #$IPTABLES -A FORWARD -o $EXTERNALIF -p tcp --dport 137 -j REJECT #$IPTABLES -A FORWARD -o $EXTERNALIF -p tcp --dport 138 -j REJECT #$IPTABLES -A FORWARD -o $EXTERNALIF -p tcp --dport 139 -j REJECT #$IPTABLES -A FORWARD -o $EXTERNALIF -p udp --dport 137 -j REJECT #$IPTABLES -A FORWARD -o $EXTERNALIF -p udp --dport 138 -j REJECT #$IPTABLES -A FORWARD -o $EXTERNALIF -p udp --dport 139 -j REJECT #$IPTABLES -A INPUT -i $EXTERNALIF -p udp --dport 137 -j REJECT #Allow ALL other forwarding going out #$IPTABLES -A FORWARD -o $EXTERNALIF -i $INTERNALIF -j ACCEPT #Allow replies coming in $IPTABLES -A FORWARD -i $EXTERNALIF -m state --state ESTABLISHED,RELATED -j ACCEPT #Whack allowances #Allow DHCP- Optus users need this #$IPTABLES -A INPUT -p udp -d 255.255.255.255 --dport 68 -j ACCEPT #Allow yourself to be a DHCP server for your inside network #Necessary because the default rule allowing valid addresses ignores broadcast $IPTABLES -A INPUT -i $INTERNALIF -p tcp --sport 68 --dport 67 -j ACCEPT $IPTABLES -A INPUT -i $INTERNALIF -p udp --sport 68 --dport 67 -j ACCEPT #Allow nameserver packets. Different versions of iptables seem to error here. #Comment out if necessary. cat /etc/resolv.conf | \ awk '/^nameserver/ {print $2}' | \ xargs -n1 $IPTABLES -A INPUT -p udp --sport 53 -j ACCEPT -s #Allow Telstra hearbeat #This section is propz to Defed #$IPTABLES -A INPUT -p udp --sport 5050 -j ACCEPT #$IPTABLES -A INPUT -p udp --sport 5051 -j ACCEPT #From here on, we're dealing with connection attempts. #The -m limit is a DoS protection on connects #First we allow a certain amount of connections per second #DROP the rest (so we don't DoS ourself with rejections) #We don't limit normal packets (!syn) by allowing the rest ##Basic services. Uncomment to allow in. # ftp-data # Funcao para permitir acesso externo a inteface. echo Portas abertas: let CONTADOR=0; for TEMP_VAR01 in ${PORTAS_LIBERADAS_TCP[@]} ; do echo Liberando acesso a porta TCP: $TEMP_VAR01 $IPTABLES -A INPUT -p tcp --dport $TEMP_VAR01 -j ACCEPT; let CONTADOR=$CONTADOR+1; done; let CONTADOR=0; for TEMP_VAR01 in ${PORTAS_LIBERADAS_UDP[@]} ; do echo Liberando acesso a porta UDP: $TEMP_VAR01 $IPTABLES -A INPUT -p udp --dport $TEMP_VAR01 -j ACCEPT; let CONTADOR=$CONTADOR+1; done; # smtp One per second limt -burst rate of ten $IPTABLES -A INPUT -p tcp --dport 25 --syn -m limit --limit 1/s \ --limit-burst 10 -j ACCEPT $IPTABLES -A INPUT -p tcp --dport 25 --syn -j DROP $IPTABLES -A INPUT -p tcp --dport 25 -j ACCEPT # ##DNAT if [ "$ATIVAREDIR" = "Y" ] ; then echo Ativando redirecionamentos da interface valida para maquinas internas if [ -f $REDIRECIONAMENTOS ]; then while read IP_PORT; do # extract the protocols, IPs and ports NAT_TYPE=$(echo "$IP_PORT" | awk '{print $1}') NAT_EXT_PORT=$(echo "$IP_PORT" | awk '{print $2}') NAT_INT_IP=$(echo "$IP_PORT" | awk '{print $3}') NAT_INT_PORT=$(echo "$IP_PORT" | awk '{print $4}') ${IPTABLES} -A PREROUTING -t nat -p $NAT_TYPE -d $EXTERNAL_IP --dport $NAT_EXT_PORT -j DNAT --to-destination $NAT_INT_IP:$NAT_INT_PORT ${IPTABLES} -A FORWARD -i $EXTERNALIF -o $INTERNALIF -p $NAT_TYPE -d $NAT_INT_IP --dport $NAT_INT_PORT -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT ${IPTABLES} -A FORWARD -i $INTERNALIF -o $EXTERNALIF -p $NAT_TYPE -s $NAT_INT_IP --sport $NAT_INT_PORT -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT ${IPTABLES} -t nat -A POSTROUTING -d $NAT_INT_IP -s $INTERNALNET -p $NAT_TYPE --dport $NAT_INT_PORT -j SNAT --to $INTERNAL_IP echo Inserida regra de redirecionamento dnat: $NAT_TYPE:$EXTERNAL_IP:$NAT_EXT_PORT - $NAT_INT_IP:$NAT_INT_PORT done < $REDIRECIONAMENTOS unset IP_PORT unset NAT_TYPE unset NAT_EXT_PORT unset NAT_INT_IP unset NAT_INT_PORT else echo "$REDIRECIONAMENTOS (tabela de redir) nao encontrado! Redirecionamento desabilitado." fi fi echo -n $VERMELHO echo "Enderecos q nao podem passar no proxy:"; echo -n $NORMAL let CONTADOR01=0; for TEMP_VAR02 in ${IPSNAOPROXY[@]} ; do echo -n $VERDE; echo "Permitindo acesso nao proxyado a: $TEMP_VAR02"; echo -n $NORMAL; $IPTABLES -A FORWARD -o $EXTERNALIF -i $INTERNALIF -s $TEMP_VAR02 -j ACCEPT; #$IPTABLES -A FORWARD -p tcp --dport 80 -d $TEMP_VAR02 -j ACCEPT; $IPTABLES -A FORWARD -p tcp -d $TEMP_VAR02 -j ACCEPT; #$IPTABLES -A FORWARD -p tcp --dport 443 -d $TEMP_VAR02 -j ACCEPT; $IPTABLES -A FORWARD -p udp -d $TEMP_VAR02 -j ACCEPT; $IPTABLES -A PREROUTING -t nat -p tcp -d $TEMP_VAR02 -j ACCEPT; let CONTADOR01=$CONTADOR01+1; done; # Proxy transparente? if [ "$ATIVAPROXY" = "Y" ] ; then echo "Ativando Proxy Transparente para ${PROXY}: " $IPTABLES -t nat -A PREROUTING -i $INTERNALIF -p tcp --dport 80 -j REDIRECT --to-port 3128 fi ##Some ports should be denied and logged. $IPTABLES -A INPUT -p tcp --dport 1433 -m limit -j LOG \ --log-prefix "Firewalled packet: MSSQL " $IPTABLES -A INPUT -p tcp --dport 1433 -j DROP $IPTABLES -A INPUT -p tcp --dport 6670 -m limit -j LOG \ --log-prefix "Firewalled packet: Deepthrt " $IPTABLES -A INPUT -p tcp --dport 6670 -j DROP $IPTABLES -A INPUT -p tcp --dport 6711 -m limit -j LOG \ --log-prefix "Firewalled packet: Sub7 " $IPTABLES -A INPUT -p tcp --dport 6711 -j DROP $IPTABLES -A INPUT -p tcp --dport 6712 -m limit -j LOG \ --log-prefix "Firewalled packet: Sub7 " $IPTABLES -A INPUT -p tcp --dport 6712 -j DROP $IPTABLES -A INPUT -p tcp --dport 6713 -m limit -j LOG \ --log-prefix "Firewalled packet: Sub7 " $IPTABLES -A INPUT -p tcp --dport 6713 -j DROP $IPTABLES -A INPUT -p tcp --dport 12345 -m limit -j LOG \ --log-prefix "Firewalled packet: Netbus " $IPTABLES -A INPUT -p tcp --dport 12345 -j DROP $IPTABLES -A INPUT -p tcp --dport 12346 -m limit -j LOG \ --log-prefix "Firewalled packet: Netbus " $IPTABLES -A INPUT -p tcp --dport 12346 -j DROP $IPTABLES -A INPUT -p tcp --dport 20034 -m limit -j LOG \ --log-prefix "Firewalled packet: Netbus " $IPTABLES -A INPUT -p tcp --dport 20034 -j DROP $IPTABLES -A INPUT -p tcp --dport 31337 -m limit -j LOG \ --log-prefix "Firewalled packet: BO " $IPTABLES -A INPUT -p tcp --dport 31337 -j DROP $IPTABLES -A INPUT -p tcp --dport 6000 -m limit -j LOG \ --log-prefix "Firewalled packet: XWin " $IPTABLES -A INPUT -p tcp --dport 6000 -j DROP #Traceroutes depend on finding a rejected port. DROP the ones it uses $IPTABLES -A INPUT -p udp --dport 33434:33523 -j DROP #Don't log ident because it gets hit all the time eg connecting to an irc server $IPTABLES -A INPUT -p tcp --dport 113 -j REJECT #Don't log igmp. Some people get too many of these $IPTABLES -A INPUT -p igmp -j REJECT #Don't log web or ssl because people surfing for long times lose connection #tracking and cause the system to create a new one, flooding logs. $IPTABLES -A INPUT -p tcp --dport 80 -j REJECT $IPTABLES -A INPUT -p tcp --dport 443 -j REJECT ##Catch all rules. #iptables reverts to these if it hasn't matched any of the previous rules. #Log. There's no point logging noise. There's too much of it. #Just log connection requests $IPTABLES -A INPUT -p tcp --syn -m limit --limit 5/minute -j LOG \ --log-prefix "Firewalled packet:" $IPTABLES -A FORWARD -p tcp --syn -m limit --limit 5/minute -j LOG \ --log-prefix "Firewalled packet:" #Reject $IPTABLES -A INPUT -p tcp -j REJECT --reject-with tcp-reset $IPTABLES -A INPUT -p all -j DROP $IPTABLES -A FORWARD -p tcp -j REJECT --reject-with tcp-reset $IPTABLES -A FORWARD -p all -j DROP #Accept it anyway if it's only output $IPTABLES -A OUTPUT -j ACCEPT #Masquerade internal connections going out. $IPTABLES -A POSTROUTING -t nat -o $EXTERNALIF -j MASQUERADE # Implementacao experimental de seguranca # Usuario teria que fazer conexao 3 vezes na porta 223 para somente assim # liberar a porta 221 para efetivar a conexao #iptables -A INPUT -p tcp -m tcp --dport 221 -m state --state NEW -m recent --rcheck --name SSH --rsource --seconds 60 --hitcount 3 -j ACCEPT #iptables -A INPUT -p tcp -m tcp --dport 222 -m state --state NEW -m recent --name SSH --remove -j DROP #iptables -A INPUT -p tcp -m tcp --dport 223 -m state --state NEW -m recent --set --name SSH --rsource -j DROP #iptables -A INPUT -p tcp -m tcp --dport 224 -m state --state NEW -m recent --name SSH --remove -j DROP exit 0
Firewall simples, com opções de redirecionamento
mPlayRecTv - assiste e grave a programação da TV com MPlayer
Imspector - Manipular ACLS facilmente
Nenhum comentário foi encontrado.
Enviar mensagem ao usuário trabalhando com as opções do php.ini
Meu Fork do Plugin de Integração do CVS para o KDevelop
Compartilhando a tela do Computador no Celular via Deskreen
Como Configurar um Túnel SSH Reverso para Acessar Sua Máquina Local a Partir de uma Máquina Remota
Configuração para desligamento automatizado de Computadores em um Ambiente Comercial
Compartilhamento de Rede com samba em modo Público/Anônimo de forma simples, rápido e fácil
Cups: Mapear/listar todas as impressoras de outro Servidor CUPS de forma rápida e fácil
Criando uma VPC na AWS via CLI
Tem como instalar o gerenciador AMD Adrenalin no Ubuntu 24.04? (9)