LSSilva
(usa Outra)
Enviado em 13/03/2020 - 09:41h
Tenho um script que faz justamente isto. Só que não gosto da idéia de usar o cron para realizar esta tarefa (de 10 em 10 minutos), prefiro criar um loop infinito com um sleep definido e manter a execução.
Eu vou passar aqui para alguém que mais precisar, porém preciso do seu e-mail para enviar o arquivo completo para você descompactar e utilizar (apesar de sugerir fortemente que você use o PFSense):
*Árvore de diretórios:
(d)-firewall
failover
firewall
initialconfig
loadbalance
log
networkcustomservices
(d)-rules
allowips
allowportsforwardtcp
allowportsforwardudp
allowportsinputtcplan
allowportsinputtcpwan
allowportsinputudplan
allowportsinputudpwan
blockedsites
(d)-service
loadbalance.service
*Segue conteúdo dos arquivos
-------------------------- Diretório: Firewall -------------------------
--> Failover:
#!/bin/bash
#Executar no rc.local nohup > /dev/null /etc/firewall/failover &
#Arquivo de Log
LOGFILE=/etc/firewall/log
#Tempo de espera para teste de conexão
tempo_espera=30
#Número de pacote do ping
numero_pacotes=2
#Internet ifaces
iflink1=ens3
iflink2=enp5s5
#Gw's
gwlink1=192.168.10.1
gwlink2=192.168.2.1
#Tables
tablelink1=200
tablelink2=201
#Ping destiny
endereco_ping_link1=8.8.8.8
endereco_ping_link2=8.8.4.4
#Arquivos balance
arquivo=/etc/firewall/loadbalance
#Não alterar
#Variáveis destinadas ao controle
i=0
link1=1
link2=1
#Ativação banlanceamento de links
sh $arquivo > /dev/null
while [ $i -le 10 ];
do
#Determining Routes
ip route add 8.8.8.8/32 via $gwlink1
ip route add 8.8.4.4/32 via $gwlink2
#Gets date
DATE=`date '+%d-%m-%Y %H:%M:%S'`
#########
#Link1###
#########
#Detecta se esta em link up antes de testar ping.
cmd_link1=$(ip addr show $iflink1 | grep state | awk '{print $9}')
if [ "$cmd_link1" != "DOWN" ]
then
cmd_link1_route=$(ip route show table $tablelink1 | awk '{print $2}')
if [ "$cmd_link1_route" != "via" ]
then
ip route add default dev $iflink1 via $gwlink1 table $tablelink1
fi
if (ping -I $iflink1 -c $numero_pacotes $endereco_ping_link1 > /dev/null)
then
link1="1"
else
link1="0"
fi
else
link1="0"
fi
#########
#Link2###
#########
#Detecta se esta em link up antes de testar ping.
cmd_link2=$(ip addr show $iflink2 | grep state | awk '{print $9}')
if [ "$cmd_link2" != "DOWN" ]
then
cmd_link2_route=$(ip route show table $tablelink2 | awk '{print $2}')
if [ "$cmd_link2_route" != "via" ]
then
ip route add default dev $iflink2 via $gwlink2 table $tablelink2
fi
if (ping -I $iflink2 -c $numero_pacotes $endereco_ping_link2 > /dev/null)
then
link2="1"
else
link2="0"
fi
else
link2="0"
fi
#Testing comparations
if [ "$link1" = "1" ] && [ "$link2" = "1" ];then
sh $arquivo > /dev/null
elif [ "$link1" = "0" ] && [ "$link2" = "1" ];then
echo -e "------------------" >> $LOGFILE
echo -e "Evento de Queda..." >> $LOGFILE
echo -e "Link L1 Inativo!" >> $LOGFILE
echo -e $DATE >> $LOGFILE
echo -e "------------------" >> $LOGFILE
ip route del default
ip route add default via $gwlink2
ip route flush cache
elif [ "$link1" = "1" ] && [ "$link2" = "0" ];then
echo -e "------------------" >> $LOGFILE
echo -e "Evento de Queda..." >> $LOGFILE
echo -e "Link L2 Invativo!" >> $LOGFILE
echo -e $DATE >> $LOGFILE
echo -e "------------------" >> $LOGFILE
ip route del default
ip route add default via $gwlink1
ip route flush cache
elif [ "$link1" = "0" ] && [ "$link2" = "0" ];then
echo -e "------------------" >> $LOGFILE
echo -e "Evento de Queda..." >> $LOGFILE
echo -e "Link L1/L2 Invativos!" >> $LOGFILE
echo -e $DATE >> $LOGFILE
echo -e "------------------" >> $LOGFILE
fi
sleep $tempo_espera
done
--> Firewall
#!/bin/bash
#vars
iflocalnet="ens2"
localnet="192.168.0.0/24"
ifwans="ens3 enp5s5"
ifwan1="ens3"
ifwan2="enp5s5"
rfc1918="10.0.0.0/8 172.16.0.0/12 192.168.0.0/16"
start (){
#Set permissive defaults
#Policy
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
#Clean
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
##############
#Filter(INPUT)
##############
#Invalid
iptables -A INPUT -m state --state INVALID -j LOG --log-prefix "Firewall: Invalid Input "
iptables -A INPUT -m state --state INVALID -j DROP
#Valid
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
#Services-Accept (TCP / LAN)
for port in $(cat /etc/firewall/rules/allowportsinputtcplan | grep -v "#")
do
iptables -A INPUT -p tcp -i $iflocalnet --dport $port -s $localnet -m state --state NEW --syn -j ACCEPT
done
#Services-Accept (UDP / LAN)
for port in $(cat /etc/firewall/rules/allowportsinputudplan | grep -v "#")
do
iptables -A INPUT -p udp -i $iflocalnet --dport $port -s $localnet -m state --state NEW -j ACCEPT
done
#Block RFC1918 SrcAddres From Wan
#for iface in $ifwans
#do
#for srcblk in $rfc1918
#do
#iptables -A INPUT -i $iface -s $srcblk -j LOG --log-prefix "Firewall: RFC1918 Manipulated IP "
#iptables -A INPUT -i $iface -s $srcblk -j DROP
#done
#done
#Services-Accept (TCP / WAN)
for port in $(cat /etc/firewall/rules/allowportsinputtcpwan | grep -v "#")
do
iptables -A INPUT -p tcp -i $ifwan1 --dport $port -m state --state NEW --syn -j ACCEPT
iptables -A INPUT -p tcp -i $ifwan2 --dport $port -m state --state NEW --syn -j ACCEPT
done
#Services-Accept (UDP / WAN)
for port in $(cat /etc/firewall/rules/allowportsinputudpwan | grep -v "#")
do
iptables -A INPUT -p udp -i $ifwan1 --dport $port -m state --state NEW -j ACCEPT
iptables -A INPUT -p udp -i $ifwan2 --dport $port -m state --state NEW -j ACCEPT
done
#Services-Accept (ICMP)
iptables -A INPUT -p icmp --icmp-type echo-request -s $localnet -j ACCEPT
#Loopback
iptables -A INPUT -i lo -j ACCEPT
#Default LOG
iptables -A INPUT ! -i lo -j LOG --log-prefix "Firewall: Drop Input "
###############
#Filter(OUTPUT)
###############
iptables -A OUTPUT -m state --state INVALID -j LOG --log-prefix "Firewall: Invalid Output "
iptables -A OUTPUT -m state --state INVALID -j DROP
################
#Filter(FORWARD)
################
#Invalid
iptables -A FORWARD -m state --state INVALID -j LOG --log-prefix "Firewall: Invalid Forward "
iptables -A FORWARD -m state --state INVALID -j DROP
#Valid
iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
#Blocked Sites
for site in $(cat /etc/firewall/rules/blockedsites | grep -v "#")
do
iptables -I FORWARD -p tcp -m multiport --dports 80,443 -s $localnet -i $iflocalnet -m string --algo bm --string $site -j DROP
done
#Ip Adress Allow FOR ALL
for ip in $(cat /etc/firewall/rules/allowips | grep -v "#")
do
iptables -I FORWARD -i $iflocalnet -s $ip -j ACCEPT
done
#Anti-Spoof Rule
iptables -A FORWARD -i $iflocalnet ! -s $localnet -j LOG --log-prefix "Firewall: Spoofed Packet "
iptables -A FORWARD -i $iflocalnet ! -s $localnet -j DROP
#Services-Accept (TCP)
for port in $(cat /etc/firewall/rules/allowportsforwardtcp | grep -v "#")
do
iptables -A FORWARD -p tcp -i $iflocalnet --dport $port -s $localnet -m state --state NEW --syn -j ACCEPT
done
#Services-Accept (UDP)
for port in $(cat /etc/firewall/rules/allowportsforwardudp | grep -v "#")
do
iptables -A FORWARD -p udp -i $iflocalnet --dport $port -s $localnet -m state --state NEW -j ACCEPT
done
#Services-Accept (ICMP)
iptables -A FORWARD -p icmp --icmp-type echo-request -s $localnet -i $iflocalnet -j ACCEPT
#Default LOG
iptables -A FORWARD ! -i lo -j LOG --log-prefix "Firewall: Drop Forward "
##################
#Nat - PreRouting
##################
#Proxy
iptables -t nat -A PREROUTING -p tcp --dport 80 -i $iflocalnet -s $localnet -j REDIRECT --to-port 3128
##################
#Nat - PostRouting
##################
for iface in $ifwans
do
iptables -t nat -A POSTROUTING -o $iface -j MASQUERADE
done
}
stop (){
#Set permissive defaults
#Policy
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
#Clean
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
#Masquerading
iptables -t nat -A POSTROUTING -j MASQUERADE
}
case $1 in
start) start;;
stop) stop;;
restart) stop;start;;
*) echo "Use";;
esac
--> initialconfig
#!/bin/bash
function modifyenv(){
echo "Creating tables on rt_tables..."
echo "200 link1">>/etc/iproute2/rt_tables
echo "201 link2">>/etc/iproute2/rt_tables
echo "Done!"
echo "Adding Configs to sysctl.conf..."
echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
echo "net.ipv4.ip_dynaddr=1" >> /etc/sysctl.conf
sysctl -p
echo "Done!"
echo "Disabling NetworkManager..."
systemctl disable NetworkManager
echo "Done!"
echo "Disabling firewalld..."
systemctl disable firewalld
echo "Done!"
echo "Disabling SeLinux..."
sed s/enforcing/permissive/g /etc/selinux/config > /etc/selinux/config.modified
mv /etc/selinux/config /etc/selinux/config.default
mv /etc/selinux/config.modified /etc/selinux/config
echo "Done!"
echo "Downloading NoIP2..."
echo "First Install Wget and GCC..."
yum install wget gcc -y
echo "Downloading file..."
cd /usr/local/src/
wget
http://www.no-ip.com/client/linux/noip-duc-linux.tar.gz
tar zxf noip-duc-linux.tar.gz
cd noip-*
make
make install
echo "Done!"
mainmenu;
}
function configurenetif(){
#Recover all interfaces on system, unless lo.
for if in $(ip addr show | grep mtu | grep -v lo | awk '{print $2}' | sed s/://g)
do
echo "Configurando Interface: $if";
echo "Getting UUID..."
uuid="cat /etc/sysconfig/network-scripts/ifcfg-$if | grep UUID"
echo "Done!"
echo "Interface terá IP estático(1) ou será dhcp(2)?";
read op;
if [ "$op" = "1" ]
then
#Static
echo "Nome Inteface:"
read nomeIface
echo "Endereço IP:"
read devIp
echo "CiDR (Apenas número):"
read devCidr
echo "DefaultRoute? (yes/no)"
read devDefRoute
echo TYPE=Ethernet > /etc/sysconfig/network-scripts/ifcfg-$if
echo PROXY_METHOD=none >> /etc/sysconfig/network-scripts/ifcfg-$if
echo BROWSER_ONLY=no >> /etc/sysconfig/network-scripts/ifcfg-$if
echo BOOTPROTO=static >> /etc/sysconfig/network-scripts/ifcfg-$if
echo DEFROUTE=$devDefRoute >> /etc/sysconfig/network-scripts/ifcfg-$if
echo IPV4_FAILURE_FATAL=no >> /etc/sysconfig/network-scripts/ifcfg-$if
echo IPV6INIT=no >> /etc/sysconfig/network-scripts/ifcfg-$if
echo IPV6_AUTOCONF=no >> /etc/sysconfig/network-scripts/ifcfg-$if
echo IPV6_DEFROUTE=no >> /etc/sysconfig/network-scripts/ifcfg-$if
echo IPV6_FAILURE_FATAL=no >> /etc/sysconfig/network-scripts/ifcfg-$if
echo IPV6_ADDR_GEN_MODE=stable-privacy >> /etc/sysconfig/network-scripts/ifcfg-$if
echo NAME=$nomeIface >> /etc/sysconfig/network-scripts/ifcfg-$if
echo DEVICE=$if >> /etc/sysconfig/network-scripts/ifcfg-$if
echo ONBOOT=yes >> /etc/sysconfig/network-scripts/ifcfg-$if
echo $uuid >> /etc/sysconfig/network-scripts/ifcfg-$if
echo IPADDR=$devIP >> /etc/sysconfig/network-scripts/ifcfg-$if
echo PREFIX=$devCidr >> /etc/sysconfig/network-scripts/ifcfg-$if
elif [ "$op" = "2" ]
then
#dhcp
echo "Nome Inteface:"
read nomeIface
echo "DefaultRoute? (yes/no)"
read devDefRoute
echo TYPE=Ethernet > /etc/sysconfig/network-scripts/ifcfg-$if
echo PROXY_METHOD=none >> /etc/sysconfig/network-scripts/ifcfg-$if
echo BROWSER_ONLY=no >> /etc/sysconfig/network-scripts/ifcfg-$if
echo BOOTPROTO=dhcp >> /etc/sysconfig/network-scripts/ifcfg-$if
echo DEFROUTE=$devDefRoute >> /etc/sysconfig/network-scripts/ifcfg-$if
echo IPV4_FAILURE_FATAL=no >> /etc/sysconfig/network-scripts/ifcfg-$if
echo IPV6INIT=no >> /etc/sysconfig/network-scripts/ifcfg-$if
echo IPV6_AUTOCONF=no >> /etc/sysconfig/network-scripts/ifcfg-$if
echo IPV6_DEFROUTE=no >> /etc/sysconfig/network-scripts/ifcfg-$if
echo IPV6_FAILURE_FATAL=no >> /etc/sysconfig/network-scripts/ifcfg-$if
echo IPV6_ADDR_GEN_MODE=stable-privacy >> /etc/sysconfig/network-scripts/ifcfg-$if
echo NAME=$nomeIface >> /etc/sysconfig/network-scripts/ifcfg-$if
echo $uuid >> /etc/sysconfig/network-scripts/ifcfg-$if
echo DEVICE=$if >> /etc/sysconfig/network-scripts/ifcfg-$if
echo ONBOOT=yes >> /etc/sysconfig/network-scripts/ifcfg-$if
fi
done
mainmenu;
}
function mainmenu() {
echo "-------------------Main Menu---------------------"
echo "-------------------------------------------------"
echo "Options: --"
echo "1 - Prepare Environment --"
echo "2 - Configure Network Interfaces --"
echo "3 - Restart Computer --"
echo "4 - Configure Squid/SquidGuard --"
echo "5 - Configure DHCP --"
echo "6 - Exit --"
echo "-------------------------------------------------"
echo "-------------------------------------------------"
read op
case $op in
"1") modifyenv;;
"2") configurenetif;;
"3") restart;;
"4") squid;;
"5") dhcp;;
"6") exit 0;;
*) echo "Opcao Invalida..."; sleep 2; mainmenu;;
esac
}
function squid() {
echo "Download Squid / SquidGuard ..."
yum install epel-release -y
yum update -y
yum install squid squidGuard -y
echo "Done!"
echo "Adjusting configuration..."
mv /etc/squid/squid.conf /etc/squid/squid.conf.def
mv /etc/squid/squidGuard.conf /etc/squid/squidGuard.conf.def
echo "Location of configuration files of squid/squidGuard:"
read localdir
cp $localdir/squid.conf /etc/squid/
cp $localdir/blacklists /etc/squid/ -fr
cp $localdir/squidGuard.conf /etc/squid/
echo "Location of squidGuard Lists:"
read listlocal
rm -f /var/squidGuard/*gz
cp $listlocal/*gz /var/squidGuard/ -fr
echo "Unpacking..."
cd /var/squidGuard/
tar zxf blacklists.tgz
tar zxf shallalist.tar.gz
mv BL shallalists
mkdir whitelist
> whitelist/domains
> whitelist/urls
echo "Adjusting permissions..."
chown squid:squid /var/squidGuard/* -R
echo "Creating - DB's squidGuard..."
squidGuard -b -C all
chown squid:squid /var/squidGuard/* -R
echo "Adjusting permissions..."
find /var/squidGuard/ -type f | xargs chmod 644
find /var/squidGuard/ -type d | xargs chmod 755
chown squid:squid /var/log/squidGuard/squidGuard.log
chmod 755 /var/log/squidGuard/squidGuard.log
echo "Creating squid swap directories..."
squid -z
echo "Addding squid on system startup..."
systemctl enable squid
}
function dhcp(){
echo "Installing dhcp..."
yum install dhcp -y
echo "Location of dhcpd configuration file:"
read dhcpconf
echo "Copying file..."
mv /etc/dhcp/dhcpd.conf /etc/dhcp/dhcpd.conf.def
cp $dhcpconf/dhcpd.conf /etc/dhcp/dhcpd.conf
echo "Adding dhcpd on system startup..."
systemctl enable dhcpd
echo "Done!"
}
function restart(){
echo "Necessário reiniciar sistema para aplicar. Deseja reiniciar agora? (y/n)"
read op
case $op in
"y") shutdown -r now;;
"s") shutdown -r now;;
"Y") shutdown -r now;;
"S") shutdown -r now;;
*) mainmenu;;
esac
}
mainmenu
-->loadbalance
#!/bin/bash
#Vars
#link1
iflink1="ens3"
tablelink1="200"
gwlink1="192.168.10.1"
netlink1="192.168.10.0/24"
pesolink1=1
#link2
iflink2="enp5s5"
tablelink2="201"
gwlink2="192.168.2.1"
netlink2="192.168.2.0/24"
pesolink2=1
#Internal
ifinternal="ens2"
internalnet="192.168.0.0/24"
#Modulos
modprobe iptable_nat
modprobe ip_nat_ftp
modprobe ipt_MARK
#Ativar tcp_syncookies, ip_forward e ip_dynaddr (feitos sysctl)
#Deleta rota padrão
ip route del default
#limpa regras tabelas
ip route flush $tablelink1
ip route flush $tablelink2
#Define rotas
ip route add default dev $iflink1 via $gwlink1 table $tablelink1
ip route add default dev $iflink2 via $gwlink2 table $tablelink2
#Define roteamento links
cmd_link1=$(ip rule show | grep $netlink1)
if [ "$cmd_link1" = "" ]; then
ip rule add from $netlink1 lookup $tablelink1
fi
cmd_link2=$(ip rule show | grep $netlink2)
if [ "$cmd_link2" = "" ]; then
ip rule add from $netlink2 lookup $tablelink2
fi
#Define as regras para balanceamento
ip route add default scope global nexthop via $gwlink1 dev $iflink1 weight $pesolink1 nexthop via $gwlink2 dev $iflink2 weight $pesolink2
#Aplica as regras
ip route flush cache
-->networkcustomservices
#!/bin/bash
#Activates network services (failover, loadbalance, firewall, ddns)
start (){
#Firewall
/etc/firewall/firewall start
#Failover
/etc/firewall/failover &
#DDNS
/usr/local/bin/noip2 &
}
stop (){
/etc/firewall/firewall stop
killall failover
killall noip2
}
case $1 in
start) start;;
stop) stop;;
*) echo "Use start/stop";;
esac
-------------------------- Diretório: Service -------------------------
--> loadbalance.service
[Unit]
Description=LoadBalance
[Service]
ExecStart=/etc/firewall/networkcustomservices start
KillMode=process
[Install]
WantedBy=multi-user.target
------------------------------------------------------------------------
No arquivo que irei enviar, caso queira, tem os arquivos nomeados "notes" que criei explicando mais a fundo o funcionamento. Se mais alguém quiser, por favor responder também.
Inclusive tem este script para 3 wans, funciona muito bem (centos7).
Mas como disse, o PFSense faz isto com alguns cliques, além de fornecer muito mais recursos de forma muito mais rápida, Kernel otimizado para isto e algumas coisas mais.