Securing SSH

  • Key based authentication is generally the safest way to use SSH

  • Key based authentication can be enabled by adding PubKeyAuthentication yes to the /etc/ssh/sshd_config file.

  • To generate an SSH key, run ssh-keygen

  • When generating a key, it is common to use ssh-keygen -t to specify what algorithm to use when generating the key.

  • Common algorithm options are rsa and ed25519

  • Another common option when generating a key is ssh-keygen -b which is used to specify the number of bits in the key.

  • A longer key means it is better protected against brute force attacks, but it also means it is more compute heavy to generate and validate.

  • The typical length is 4096

  • The command should look something like ssh-keygen -t ed25519 -b 4096

  • When you generate an ssh key, it will ask you to input a password that will be required when that key is used.

  • In some usecases, you may not want to have a password protected key. For example, if you need to automate an SSH connection, it may be unnecessarily complicated to automate password entry.

  • When you run ssh-keygen, two files are created in that users ~/.ssh/ directory. Those files are id_rsa & id_rsa.pub

  • id_rsa is your private SSH key. Its permissions should be set so that only the user that generated it can access it.

  • id_rsa.pub is your public SSH key. This will be placed in the remote hosts ~/.ssh/authorized-keys file to grant SSH access to that user.

  • you can add a key to a remote host by running ssh-copy-id user@host

  • For example ssh-copy-id username@1.1.1.1 or ssh-copy-id username@mydomain.com

  • SSH key authentication can be enforced by disabling password authentication by adding PasswordAuthentication no to the /etc/ssh/sshd_config file.

  • Disabling password authentication to SSH is generally good practice as SSH keys are effectively impossible to brute force.

  • You should never log in directly to the root user.

  • When setting up a remote host initially it is OK to log in as the root user to get other accounts set up, but then SSH access should quickly be disabled.

  • To prevent root logins via ssh, add PermitRootLogin no to the /etc/ssh/sshd_config file.

  • If you need acccess the root user, you should do so by SSHing into your personal user, and then switching to the root user using sudo su -

  • sshd_config

  • Specific users can be granted SSH access by adding AllowUsers username0 username1 username 2

  • The same can be done for groups AllowGroups group0 group1 group2

  • Groups & users can be denied SSH access by adding DenyUsers or DenyGroups

  • The SSH banner should be disabled by adding Banner none as the information it provides may be used by attackers.

  • Changes to sshd_config will not apply until the application has been reloaded.

  • This can generally be done by running systemctl reload sshd