#!/bin/bash
SCRIPT_NAME="f2b+ufw.sh"

# Registra el inicio en /opt/curl.txt
echo "Inicio: $SCRIPT_NAME" >> /opt/curl.txt
if systemctl status iptables-persistent |grep active >/dev/null 2>&1
then 
 sudo systemctl stop iptables-persistent
 sudo systemctl disable iptables-persistent

fi
if systemctl status iptables |grep active >/dev/null 2>&1
then 
 sudo systemctl stop iptables
 sudo systemctl disable iptables

fi

#ufw
apps=("ufw")

# Función para verificar e instalar una aplicación
check_and_install() {
    app=$1
    if ! dpkg -s $app 2>/dev/null | grep -q "Status: install ok installed"; then
        echo "$app no está instalado. Instalando..."
        sudo apt-get install -y $app
        echo "$app instalado correctamente."
    else
        echo "$app ya está instalado."
    fi
}

# Verificar e instalar cada aplicación
for app in "${apps[@]}"; do
    check_and_install $app
done


sudo ufw allow 22/tcp
sudo ufw default deny incoming
sudo ufw default allow outgoing

#fail2ban
if [ -f "/var/log/auth.log" ]
then
   rm /var/log/auth.log
 #echo "found file"

fi

sudo systemctl enable rsyslog
sudo systemctl restart rsyslog

apps=("fail2ban")

# Función para verificar e instalar una aplicación
check_and_install() {
    app=$1
    if ! dpkg -s $app 2>/dev/null | grep -q "Status: install ok installed"; then
        echo "$app no está instalado. Instalando..."
        sudo apt-get install -y $app
        echo "$app instalado correctamente."
    else
        echo "$app ya está instalado."
    fi
}

# Verificar e instalar cada aplicación
for app in "${apps[@]}"; do
    check_and_install $app
done

sudo cat > /etc/fail2ban/jail.local <<- "EOF"
[sshd]
enabled = true
filter = sshd
mode = normal
banaction = ufw
port = 22
protocol = tcp
logpath = /var/log/auth.log
maxretry = 1
bantime = 1h
findtime = 30m
ignoreip = 127.0.0.0/8 ::1

[ufw]
enabled = true
filter = ufw.aggressive
action = iptables-allports
logpath = /var/log/ufw.log
maxretry = 1
bantime = 1m


EOF
sudo cat > /etc/fail2ban/filter.d/ufw.aggressive.conf <<- "EOF"
[Definition]
failregex = [UFW BLOCK].+SRC=<HOST> DST
ignoreregex =

EOF

sudo cat > /bin/auto-ufw.sh <<- "EOF"
#!/bin/bash

start=$(date +"%Y-%m-%d %T")

    whiptail --title "Menu UFW" --inputbox "press A for add or R to remove rules:" 10 60 2>/tmp/rulex.txt
    if [ $? -ne 0 ]; then
        echo "Has elegido cancelar. Saliendo..."
        break
    fi
    
    rulex=$(cat /tmp/rulex.txt)
if [ -z "$rulex" ]; then
 exit 0
elif [ $rulex = A ]; then
 rulex=a
elif [ $rulex = a ]; then
 rulex=a
elif [ $rulex = R ]; then
 rulex=r
elif [ $rulex = r ]; then
 rulex=r
else
 exit 0
fi
    whiptail --title "Menu UFW" --inputbox "press I, O or B to: in, out or both." 10 60 2>/tmp/rulev.txt
    if [ $? -ne 0 ]; then
        echo "Has elegido cancelar. Saliendo..."
        break
    fi
    
    rulev=$(cat /tmp/rulev.txt)
if [ -z "$rulev" ]; then
 exit 0
elif [ $rulev = i ]; then
 rulev=i
elif [ $rulev = I ]; then
 rulev=i
elif [ $rulev = o ]; then
 rulev=o
elif [ $rulev = O ]; then
 rulev=o
elif [ $rulev = b ]; then
 rulev=b
elif [ $rulev = B ]; then
 rulev=b
fi
    whiptail --title "Menu UFW" --inputbox "press T to tcp, U to udp, or B to both:" 10 60 2>/tmp/portx.txt
    if [ $? -ne 0 ]; then
        echo "Has elegido cancelar. Saliendo..."
        break
    fi
    
    portx=$(cat /tmp/portx.txt)
if [ -z "$portx" ]; then
 exit 0
elif [ $portx = t ]; then
 portx=t
elif [ $portx = T ]; then
 portx=t
elif [ $portx = u ]; then
 portx=u
elif [ $portx = U ]; then
 portx=u
elif [ $portx = b ]; then
 portx=b
elif [ $portx = B ]; then
 portx=b
fi
while :
do
    whiptail --title "Menu UFW" --inputbox "Port number:" 10 60 2>/tmp/proto.txt
    if [ $? -ne 0 ]; then
        echo "Has elegido cancelar. Saliendo..."
        break
    fi
    
    proto=$(cat /tmp/proto.txt)
if [ -z "$proto" ]; then
 exit 0
fi

add_rule() {

  local regex="${port}\/${proto}"
  local rule=$(/usr/sbin/ufw status numbered | grep $regex)
  if [ -z "$rule" ]; then
      /usr/sbin/ufw allow ${proto}${port2}${port}
      echo "${start} ADDED: ${proto} ${port}"
  else
        echo "${start} EXISTS: ${proto} ${port}"
  fi
}

add_rule2() {

  local regex="${port}\/${proto}"
  local rule=$(/usr/sbin/ufw status numbered | grep $regex)
  if [ -z "$rule" ]; then
      /usr/sbin/ufw allow out to any port ${proto}
      echo "${start} ADDED: ${proto} ${port}"
  else
        echo "${start} EXISTS: ${proto} ${port}"
  fi
}


delete_rule() {

  local regex="${port}\/${proto}"
  local rule=$(/usr/sbin/ufw status numbered | grep $regex)
  if [ -z "$rule" ]; then
      /usr/sbin/ufw delete allow ${proto}${port2}${port}
        echo "${start} DELETED: ${proto} ${port}"
  else
        echo "${start} NO DELETE: rule does not exist"
  fi
}

delete_rule2() {

  local regex="${port}\/${proto}"
  local rule=$(/usr/sbin/ufw status numbered | grep $regex)
  if [ -z "$rule" ]; then
      /usr/sbin/ufw delete allow out to any port ${proto}
        echo "${start} DELETED: ${proto} ${port}"
  else
        echo "${start} NO DELETE: rule does not exist"
  fi
}

delete_rule3() {

  local regex1="tcp\/${proto}"
  local regex2="udp\/${proto}"
  local rule1=$(/usr/sbin/ufw status numbered | grep $regex1)
  local rule2=$(/usr/sbin/ufw status numbered | grep $regex2)
  if [ -z "$rule1" ]; then
      /usr/sbin/ufw delete allow ${proto}/tcp
       echo "${start} DELETED: ${proto} tcp"
  else
        echo "${start} NO DELETE: rule does not exist"
  fi
  if [ -z "$rule2" ]; then
      /usr/sbin/ufw delete allow ${proto}/udp
       echo "${start} DELETED: ${proto} udp"
  else
        echo "${start} NO DELETE: rule does not exist"
  fi
}

if [ $portx = b ]
then 
       port=""
elif [ $portx = t ]
then
      port=tcp
elif [ $portx = u ]
then
      port=udp
else
 exit 0
fi
#
if [ -z "$port" ]
then 
       port2=""
elif [ $port = tcp ]
then
      port2=/
elif [ $port = udp ]
then
      port2=/
fi
#
if [ $rulev = i ] && [ $rulex = a ]
then
        add_rule $proto $port
elif [ $rulev = i ] && [ $rulex = r ]
then
   delete_rule $proto $port
elif [ $rulev = o ] && [ $rulex = a ]
then
        add_rule2 $proto $port
elif [ $rulev = o ] && [ $rulex = r ]
then
   delete_rule2 $proto $port
elif [ $rulev = b ] && [ $rulex = a ]
then
    add_rule $proto $port
    add_rule2 $proto $port
elif [ $rulev = b ] && [ $rulex = r ]
then
   delete_rule $proto $port
   delete_rule2 $proto $port
   delete_rule3 $proto
fi
    whiptail --title "Menu UFW" --inputbox "Other port Y or N:" 10 60 2>/tmp/rulex1.txt
    if [ $? -ne 0 ]; then
        echo "Has elegido cancelar. Saliendo..."
        break
    fi
    
    rulex1=$(cat /tmp/rulex1.txt)
if [ -z "$rulex1" ]; then
 exit 0
elif [ $rulex1 = n ]; then
  exit 0
elif [ $rulex1 = N ]; then
  exit 0
elif [ $rulex1 = y ]; then
  echo ""
elif [ $rulex1 = Y ]; then
  echo ""
else
 exit 0
fi

done

EOF
chmod +x /bin/auto-ufw.sh
sudo systemctl daemon-reload
ufw disable
sudo systemctl stop fail2ban.service
sudo systemctl disable fail2ban.service
# Registra el final en /opt/curl.txt
echo "Finalizado: $SCRIPT_NAME" >> /opt/curl.txt
