Password authentication is good but can be dangerous, because it is weak against brute force attacks. There are some mechanisms which allow to mitigate this treat. There are also safer authentication mechanisms for SSH, like public key auhtentication.
We’re going to create a key pair from our client, a public and a private. We send the public key to the server. Thus, when the client tries to connect, the server communicates by encrypting communications with the public key. Only the client owning the private key will be able to understand messages from the server and initiate the connection.
Note: Asymmetric encryption is only used for authentication. Once the conenction is established, the server generates a secret key which is sent to the client. This transmission is encrypted with the public key. The secret key is then used to encrypt all communications for the session, in order to save resources. Indeed, asymmetric encryption consumes a lot more resources than symmetric encryption.
Before anything else, we verify the SSH server configuration:
RSAAuthentication yes PubkeyAuthentication yes
Then we have the creation of the key pair on the client. The following comnands must be launched as the user you want to be on the server.
$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/jean-pierre/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/jean-pierre/.ssh/id_rsa. Your public key has been saved in /home/jean-pierre/.ssh/id_rsa.pub. The key fingerprint is: 5d:c9:d4:c6:3a:8d:0b:10:33:32:9c:53:55:a1:d0:61 jean-pierre@velo
You can generate DSA keys using -t dsa.
I recommend to enter a passphrase: it is used to encrypt (symmetric encryption) the private key, which adds an additional security layer.
We now just need to send the public key, either on your own if you can, or contact the server administrator. If you have the hand on the server, there are two ways to do it:
- The ssh-copy-id command
- Manual copy
ssh-copy-id, which must be launched from the client, copies the public key specified as parameter (-i) into the ~/.ssh/authorized_keys file on the server.
$ ssh-copy-id -i id_rsa.pub [user@]host
After that, you should be able to connect via the public key. If you didn’t type any passphrase during the keys generation, no password will be asked. Otherwise, the passprhrase of the private key will be needed. Typing this passphrase at each conenction can be unpleasant. Fortunately, here comes the SSH agent, which will keep the key in memory for you.
ssh-agent displays environment vairables you have to declare. So here you go. Then:
$ ssh-add Enter passphrase for /home/jean-pierre/.ssh/id_dsa: Identity added: /home/jean-pierre/.ssh/id_dsa (/home/jean-pierre/.ssh/id_dsa)
Well done. To do after each reboot.
You can now disable password authentication and login using pubkey authentication.