Reference: https://www.linode.com/docs/guides/securing-your-server/
After deploying a linux distribution to cloud servers, we should follow some best practices to protect our server. Here’s my note of basic configs.
Add a Limit User
We should never use root
account to run our code.
adduser <username>
# add the user to `sudo` group
adduser <username> sudo
Copy Public Key
ssh-copy-id -i ~/.ssh/xxx.pub <username>@<ip>
Then we could login to our server using the new account.
Disable Root Login Over SSH
Modify the following options in `/etc/ssh/sshd_config`.
sudo vim /etc/ssh/sshd_configPermitRootLogin no
PasswordAuthentication no# only ipv4
AddressFamily inet# change ssh port from `22` to what you specify
Port 2345
After modifying the file, we’re going to enable ssh in ufw
.
sudo ufw allow 2345/tcp
sudo ufw allow ssh
sudo ufw enable
Protect SSH Login From Brute-Force Attacks
Create our own .local
config to overwrite default configurations.
sudo apt-get install fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo vim /etc/fail2ban/jail.local# find the [sshd] section, and add:
enabled = true
port = <your custom ssh port>
We could reboot our server to reload everything. In order to verify our fail2ban
config, we could use incorrect user to connect to our server. Note that our IP will be banned for a while. We will have to open a web console from your VPS admin panel and unlock your IP.
# After 3 times, your IP will be banned
ssh -p 2345 invalid@<server ip>---# In the web console such as LISH console of linode, list your chains.
sudo iptables -n -L | grep f2b-sshd -A 5# There will be an f2b-sshd chain, and the banned IP will be in the source column. Use the `fail2ban-client` to unban the IP.
sudo fail2ban-client set sshd unbanip <banned IP># If you forget your jail name, list it again
sudo fail2ban-client status
Upgrade System Automatically
sudo apt install unattended-upgrades
sudo systemctl enable unattended-upgrades
sudo systemctl start unattended-upgrades# edit default config. Note that the unattended-upgrades is not enabled yet.sudo vim /etc/apt/apt.conf.d/50unattended-upgrades
Remove the comment symbol //
from those options, and enable them:
"${distro_id}:${distro_codename}-security";---Remove-Unused-Kernel-Packages true
Remove-New-Unused-Dependencies true
Remove-Unused-Dependencies true---Unattended-Upgrade::Automatic-Reboot "false";
Let’s enable the auto-upgrades by editing `/etc/apt/apt.conf.d/20auto-upgrades`.
sudo vim /etc/apt/apt.conf.d/20auto-upgrades// 1 enables auto-update, 0 disables it.
APT::Periodic::Update-Package-Lists "1";// 1 enables auto-upgrade, 0 disables it.
APT::Periodic::Unattended-Upgrade "1";// Clean packages automatically for 7 days.
APT::Periodic::AutocleanInterval "7";
Test it using the dry-run command:
sudo unattended-upgrades --dry-run --debug