Guest User

Untitled

a guest
Nov 21st, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. VERBOSE=0
  4. QUIET=0
  5. SERVER=
  6. while getopts "vqs:" opt; do
  7. case $opt in
  8. v)
  9. VERBOSE=1
  10. ;;
  11. q)
  12. QUIET=1
  13. ;;
  14. s)
  15. SERVER="$OPTARG"
  16. ;;
  17. esac
  18. done
  19.  
  20. HOSTS_ALLOW=/etc/ufw-dynamic-hosts.allow
  21. IPS_ALLOW=/var/tmp/ufw-dynamic-ips.allow
  22.  
  23. UFW=/usr/sbin/ufw
  24. DIG=/usr/bin/dig
  25.  
  26. log() {
  27. local txt=$1
  28.  
  29. if [ "$QUIET" == 0 -a "$VERBOSE" == "1" ]; then
  30. echo "$txt"
  31. fi
  32. }
  33.  
  34. warn() {
  35. local txt=$1
  36.  
  37. if [ "$QUIET" == 0 ]; then
  38. echo "$txt" 1>&2
  39. fi
  40. }
  41.  
  42. add_rule() {
  43. local proto=$1
  44. local port=$2
  45. local ip=$3
  46. local regex="${port}\/${proto}.*ALLOW.*IN.*${ip}"
  47. local rule=$($UFW status numbered | grep $regex)
  48. if [ -z "$rule" ]; then
  49. log "Allow access from ${ip} to port ${port} on ${proto}"
  50. warn $($UFW allow proto ${proto} from ${ip} to any port ${port})
  51. else
  52. log "rule already exists. nothing to do."
  53. fi
  54. }
  55.  
  56. delete_rule() {
  57. local proto=$1
  58. local port=$2
  59. local ip=$3
  60. local regex="${port}\/${proto}.*ALLOW.*IN.*${ip}"
  61. local rule=$($UFW status numbered | grep $regex)
  62. if [ -n "$rule" ]; then
  63. log "Forbid access from ${ip} to port ${port} on ${proto}"
  64. warn $($UFW delete allow proto ${proto} from ${ip} to any port ${port})
  65. else
  66. log "rule does not exist. nothing to do."
  67. fi
  68. }
  69.  
  70.  
  71. sed '/^[[:space:]]*$/d' ${HOSTS_ALLOW} | sed '/^[[:space:]]*#/d' | while read line
  72. do
  73. proto=$(echo ${line} | cut -d: -f1)
  74. port=$(echo ${line} | cut -d: -f2 | sed 's/-/:/g')
  75. host=$(echo ${line} | cut -d: -f3)
  76.  
  77. if [ -f ${IPS_ALLOW} ]; then
  78. old_ip=$(cat ${IPS_ALLOW} | grep ${host} | cut -d: -f2)
  79. fi
  80.  
  81. if [ -z ${SERVER} ]; then
  82. ip=$($DIG +short $host | tail -n 1)
  83. else
  84. ip=$($DIG +short @${SERVER} $host | tail -n 1)
  85. fi
  86. if [ -z ${ip} ]; then
  87. if [ -n "${old_ip}" ]; then
  88. delete_rule $proto $port $old_ip
  89. fi
  90. warn "Failed to resolve the ip address of ${host}."
  91. fi
  92.  
  93. if [ -n "${old_ip}" ]; then
  94. if [ ${ip} != ${old_ip} ]; then
  95. delete_rule $proto $port $old_ip
  96. fi
  97. fi
  98. add_rule $proto $port $ip
  99. if [ -f ${IPS_ALLOW} ]; then
  100. sed -i.bak /^${host}*/d ${IPS_ALLOW}
  101. fi
  102. echo "${host}:${ip}" >> ${IPS_ALLOW}
  103. sleep 1
  104. done
Add Comment
Please, Sign In to add comment