When you run your own webserver, like I do, you constantly battle people who try to take control of your server. In order to prevent this from happening you need to be quite defensive. First; always update your server, make sure security patches are installed automatically and ensure any attempt at logging into your server is stopped as soon as possible. For the last measure you can use the
In this article we will go an setup this application to take care of attacks on the
nginx services. These commands are valid for an Ubuntu Linux server.
First, lets install the application and the addon to iptables that will make rules persistent.
sudo apt-get update sudo apt-get install iptables-persistent fail2ban
With the application on our server we create a local definition of our jail and edit the file.
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local sudo nano /etc/fail2ban/jail.local
In this file we need to set a few values in order to get it working for my taste. Look up the keys and set them to these values.
ignoreip = 127.0.0.1/8 your-home-ip bantime = 1800 destemail = firstname.lastname@example.org action = %(action_mwl)s
This ensure that actions on the server does not block itself (127.0.0.1) and that you cannot block your home computer. When someone is blocked, they are so for 30 minutes (1800 seconds). When this happens; send an email to you with the details of the block.
Now, look up the service for
nginx-http-auth further down the file and set their
enabled key to the value
true. I also set any maxretry to
In order to be even better off, lets only allow ports 22 (ssh), 80 (http) and 443 (https) to our server.
sudo iptables -A INPUT -i lo -j ACCEPT sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT sudo iptables -A INPUT -j DROP sudo iptables -S
If you are confident that you will not need to be at different locations when using ssh, you might even further tighten the rules by specifying your home IP for the rule.
sudo iptables -I INPUT -p tcp -s your-ip --dport 22 -j ACCEPT
Now, lets restart fail2ban to make sure all changes take effect.
sudo service fail2ban restart
Alright, so if someone tries something funny, they will be met with a ban! So, if you would try to ssh to your server from another server using a wrong password, you will get blocked after 3 attempts.
After a while, check out the log at
/var/log/fail2ban.log to see if it banned anybody. You can also run
iptables -S to see all the current active rules, including the ban of specific IP addresses.