Securing SSH
-
Key based authentication is generally the safest way to use SSH
-
Key based authentication can be enabled by adding
PubKeyAuthentication yesto the/etc/ssh/sshd_configfile. -
To generate an SSH key, run
ssh-keygen -
When generating a key, it is common to use
ssh-keygen -tto 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 -bwhich 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.1orssh-copy-id username@mydomain.com -
SSH key authentication can be enforced by disabling password authentication by adding
PasswordAuthentication noto the/etc/ssh/sshd_configfile. -
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 noto the/etc/ssh/sshd_configfile. -
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
DenyUsersorDenyGroups -
The SSH banner should be disabled by adding
Banner noneas 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