Linux - SSH Key Authentication

One of the most secure ways to connect to a system is with SSH key authentication that, combined with good firewall rules it can prevent all sorts of attacks.

Step 01 - Creating the Keys

Let's generate a key pair with the command below :

tiago@desktop:/$ ssh-keygen -b 4096 -t rsa -C "Home - Desktop" -N your_password

I like to add a comment and a password to my key. The password might add an extra step when logging in, but if the key is unprotected and it gets leaked is the password that will protect your keys.

Let's breakdown the options used in our command :

-b bits of the key.

-t type of the key.

-C A comment is useful when using a key manager.

-N Defines the password. It is recommended to clear your history after the command with the command history -c.

The keys will be generated by default in the following folder :

/home/user/.ssh/id_rsa - for the private key.
/home/user/.ssh/ - for the public key.

Step 02 - Configure the SSH Service

Edit your configuration file as follows :

Port 22
PermitRootLogin prohibit-password
StrictMode yes
MaxAuthTries 6
PubkeyAuthentication yes
AuthorizedKeysFile      .ssh/authorized_keys .ssh/authorized_keys2
PaswordAuthentication no
PermitEmptyPasswords no

Step 03 - Allow the Keys

We need to allow the login of our recently created pair of keys :

tiago@desktop:~/.ssh$ touch authorized_keys
tiago@desktop:~/.ssh$ chmod 0600 authorized_keys
tiago@desktop:~/.ssh$ cat id_rsa >> authorized_keys

Restart the SSH service.

tiago@desktop:/$ sudo service ssh restart

We are now able to SSH into our servers with the recently created keys and no other form of login is allowed.

Share Tweet Send
You've successfully subscribed to Infoitech - [B]logging
Great! Next, complete checkout for full access to Infoitech - [B]logging
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.