SSH access with private and public key

Default featured post

Using SSH access with password is so risky and most probably your server will be compromised in a day or two by brute force attack. The best approach to handle this issue is setting up key pairs and disable password access to server. To do so you need to do following steps.

  • Generate keys
  • Keep private key, copy public key to the server
  • Rename the public key to authorized_keys
  • Move the file to .ssh directory
  • Change permission to 700 for .ssh directory
  • Change permission of public key to 644
  • Open ssh config file (sshd_config), add the username to the bottom of the file
  • In sshd_config disable password access
  • Restart the ssh service
  • Use -i command to access (For sftp can use the same)
  • Disable password access

First let’s start with keys generation. In your local machine you need to run the following commands to generate public key (.pub) and private key.

$ ssh-keygen -t rsa

Bear in mind not to share your private key and always keep it in a safe place because of two reasons. Firstly, if you lose the key, you won’t be able to access to the server anymore. Secondly, if the key get stolen, your server will be liable to get compromised.

The next step is to rename the .pub key to authorized_keys, but before that copy the public key to your server either using scp, ftp or any other commands/tools.

For renaming you can use mv command,

$ mv myPublicKey.pub authorized_keys

After that you need to move the key to .ssh directory in your server, before that make sure .ssh directory is there. If not there create by this command,

$ mkdir .ssh

And move the key,

$ mv authorized_key .ssh

Now it is time to set permission for both .ssh directory and authorized_keys file. This step is so crucial because if you don’t have correct permission set, you .will get public keys denied error which apparently pretty much annoying to settle. Therefore, to minimize the pain, better set correct permission in the first place,

$ chmod 700 .ssh
$ chmod 644 authorized_keys

The next step is to open up ssh config file and check whether your user can ssh or not. If doesn’t have permission need to add. To do so,

$ sudo vim /etc/ssh/sshd_config

Go to the bottom of the file, and add your username if not exist. Finally, the last step is to disable password access. In the same file search for PasswordAuthentication and change the value from yes to no. Save the file and restart ssh service with this command,

$ sudo /etc/init.d/sshd restart

If you want to connect from your local machine to server, need to run this command.

$ ssh -i privateKey myUsername@myserver

To see the log of ssh you can use -v switch like this,

$ ssh -vi privateKey myUsername@myserver