You can automate this whole process using this ansible role.
Host keys need to be unique. Cloud or dedicated server providers usually have a script to generate this automatically but it’s best to do it yourself anyway in case they didn’t do it.
ssh-keygen -o -f /etc/ssh/ssh_host_rsa_key -N '' -t rsa -b 4096
ssh-keygen -o -f /etc/ssh/ssh_host_ed25519_key -N '' -t ed25519
This user will be used to login remotely to get basic access to the system.
adduser yourusername
Later, we will only allows members of this group to login via SSH.
addgroup sshusers
gpasswd -a yourusername sshusers
Paste the contents of your SSH public key from your computer to the /home/yourusername/.ssh/authorized_keys
file.
chmod 700 .ssh
chmod 600 .ssh/*
Check if login with this public key works.
Replace the contents of your /etc/ssh/sshd_config
file with what’s in this gist.
Edit the file and change the port number from 22 to something else if you want. This will avoid attacks from script kiddies trying to bruteforce your ssh.
By default, we will allow all outgoing connections and restrict access to specific ports for incoming connections.
ufw default deny incoming
ufw default allow outgoing
Enable the ssh port you setup earlier:
ufw allow <your-port-number-from-before>
Enable ufw now:
ufw enable
systemctl reload sshd
echo myhostname > /etc/hostname
Add it to /etc/hosts
as well:
echo 127.0.1.1 myhostname >> /etc/hosts
Your new setup should now be quite robust. Enjoy!
Follow me on Twitter @iamconfuzeus to get updates.
© Michael Karamuth 2022