#!/bin/bash
#############################################################################
#                                                                           #
#  With ipdrop you can add/remove ip's to/from the drop list of iptables.   #
#  Depends on: iptables                                                     #
#                                                                           #
#  Created by Koentje  (remon@cobrasoft.nl                                  #
#                                                                           #
#                                                             version 1.0   #
#############################################################################

x=0

if [ "$1" = "" ]; then
  echo -e "\n Block/unblock ip address"
  echo -e "\n Usage: $(basename $0) [block|unblock|list] (<ip>)\n"
  echo -e " Ex: $(basename $0) block 99.85.21.20"
  echo -e "     $(basename $0) unblock 99.85.21.20"
  echo -e "     $(basename $0) list\n"

elif [ "$1" = "block" ]; then
   echo -e "\n Block ip address $2\n"
   while read -r line
   do
       ipt=$(echo "$line" | awk '{print $4}')
       if [ "$ipt" = "$2" ]; then
         echo -e "\e[31m IP already in DROP list!\e[m\n"
         exit
       else
         x=1
       fi
   done< <(sudo iptables -n -L | grep DROP)
   if [ "$x" = "1" ]; then
     sudo iptables -A INPUT -s $2 -j DROP
     sudo iptables -n -L | grep 'DROP'
     echo
   fi

elif [ "$1" = "unblock" ]; then
  echo -e "\n Unblock ip address $2\n"
  sudo iptables -D INPUT -s $2 -j DROP
  sudo iptables -n -L | grep 'DROP'
  echo
elif [ "$1" = "list" ]; then
  echo -e "\n List blocked ip addresses\n"
  sudo iptables -n -L | grep 'DROP'
  echo
fi
