2 # Adds an IP to the /etc/hosts.deny file
3 # Requirements: sshd and other binaries with tcp wrappers support
5 # Author: Daniel B. Cid
6 # Last modified: Nov 09, 2005
16 LOCK="${PWD}/host-deny-lock"
17 LOCK_PID="${PWD}/host-deny-lock/pid"
21 # This number should be more than enough (even if a hundred
22 # instances of this script is ran together). If you have
23 # a really loaded env, you can increase it to 75 or 100.
33 mkdir ${LOCK} > /dev/null 2>&1
35 if [ "${MSL}" = "0" ]; then
36 # Lock acquired (setting the pid)
37 echo "$$" > ${LOCK_PID}
41 # Getting currently/saved PID locking the file
42 C_PID=`cat ${LOCK_PID} 2>/dev/null`
43 if [ "x" = "x${S_PID}" ]; then
47 # Breaking out of the loop after X attempts
48 if [ "x${C_PID}" = "x${S_PID}" ]; then
56 # So i increments 2 by 2 if the pid does not change.
57 # If the pid keeps changing, we will increments one
58 # by one and fail after MAX_ITERACTION
59 if [ "$i" = "${MAX_ITERATION}" ]; then
60 echo "`date` Unable to execute. Locked: $0" \
61 >> ${PWD}/ossec-hids-responses.log
63 # Unlocking and exiting
78 echo "`date` $0 $1 $2 $3 $4 $5" >> ${PWD}/../logs/active-responses.log
81 # IP Address must be provided
82 if [ "x${IP}" = "x" ]; then
83 echo "$0: Missing argument <action> <user> (ip)"
88 # Checking for invalid entries (lacking "." or ":", etc)
89 echo "${IP}" | egrep "\.|\:" > /dev/null 2>&1
91 echo "`date` Invalid ip/hostname entry: ${IP}" >> ${PWD}/../logs/active-responses.log
96 # Adding the ip to hosts.deny
97 if [ "x${ACTION}" = "xadd" ]; then
98 # Looking for duplication
99 IPKEY=$(grep -w "${IP}" /etc/hosts.deny)
100 if [ ! -z "$IPKEY" ]; then
101 echo "IP ${IP} already exists on host.deny..." >> ${PWD}/../logs/active-responses.log
105 echo "${IP}" | grep "\:" > /dev/null 2>&1
109 if [ "X$UNAME" = "XFreeBSD" ]; then
110 echo "ALL : ${IP} : deny" >> /etc/hosts.allow
112 echo "ALL:${IP}" >> /etc/hosts.deny
118 # Deleting from hosts.deny
119 elif [ "x${ACTION}" = "xdelete" ]; then
121 TMP_FILE=`mktemp ${PWD}/ossec-hosts.XXXXXXXXXX`
122 if [ "X${TMP_FILE}" = "X" ]; then
123 # Cheap fake tmpfile, but should be harder then no random data
124 TMP_FILE="${PWD}/ossec-hosts.`cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -1 `"
126 echo "${IP}" | grep "\:" > /dev/null 2>&1
130 if [ "X$UNAME" = "XFreeBSD" ]; then
131 cat /etc/hosts.allow | grep -v "ALL : ${IP} : deny$"> ${TMP_FILE}
132 mv ${TMP_FILE} /etc/hosts.allow
134 cat /etc/hosts.deny | grep -v "ALL:${IP}$"> ${TMP_FILE}
135 cat ${TMP_FILE} > /etc/hosts.deny
144 echo "$0: invalid action: ${ACTION}"