Cybersecurity is one of the most important parts of software development, especially when it comes to public servers. So we will start from scratch and first of all configure the server for proper protection. We will use standard UFW and fail2ban for authorization protection.
First of all, update server:
apt update -y
UFW configuration
UFW will be our first line of defence. We should close all possible access to our server except those ports we open intentionally.
One service is mandatory - OpenSSH. If we accidently forgot to allow it - access to server will be loost completely, except access trough web console in server web panel (like Dropplet console on DigitalOcean):
ufw allow OpenSSH
Other services is optional, and depending on our needs. For website, or other HTTP depending resources we should open next ports:
- 80/tcp - common http unencrypted traffic
- 443/tcp - encrypted https traffic
- 443/udp - modern http3 traffic
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow 443/udp
And now we can safely enable UFW:
ufw enable
ufw status
Fail2Ban configuration
Fail2ban - is software designed for securing user authorization. It will protect login process from Brute Force attack.
apt install fail2ban
Now, we declare our protection rules. We allow maximum of 3 failed auth retry, after which IP address of person, who tried to auth, will be banned for 1 hour. Open file
nano /etc/fail2ban/jail.d/sshd.local
And in the end of this file add next section:
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 1h
Now we can start our fail2ban service:
systemctl start fail2ban
systemctl enable fail2ban
fail2ban-client status
User registration
User Root can do too much, so we create other user and give him sudo privileges, and remove password request for sudo commands:
Create non-root user:
adduser www
Add sudo privileges for new user:
usermod -aG sudo www
Disable password confirmation for sudo - we will use auth via keys:
visudo
In the end of file add next line:
www ALL=(ALL) NOPASSWD:ALL
And disconnect from server
exit
That's all. We can forget about root user and use only our www.
It's time to configure access by keys. The simplest way to do it is by using ssh-copy-id on your local machine (install it if not installed):
ssh-copy-id www@server-id-address
It will automaticly copy your ~/.ssh/id_rsa.pub to authorized_keys on server.
If you want to do it manual - then on server create file
touch ~/.ssh/authorized_keys
Copy our local ~/.ssh/id_rsa.pub content and paste it into server's ~/.ssh/authorized_keys
And (it's important) change access rights to ssh and file
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
Access by key is configured, password will never be asked again. That's it, server protection configured and you can safely deploy your appliaction!