SSH works by encrypting the communications between the client and the server. To use it, you can either authenticate with a password, which is prone to attacks by bruteforce, or use key pair authentication, which is simpler and safer.
To do this, you will have to generate a key pair, consisting of a public and private key. Do not communicate your private key to anyone, best is to limit the rights on this file to only you. To generate those keys, use the following command :
$ ssh-keygen -f /home/user/.ssh/id_test
-f option specifies where the pair will be saved. The
.ssh folder in your home directory is the default place for the keys and the
authorized_keys file, where all authorized public keys are listed. By default, the RSA cryptosystem will be used, you can specify another method with the
-d option. Take care that you will have weird behaviours if you use a different method.
Then you will be prompt for a password, it will be asked each time the key is loaded in your
Enter passphrase (empty for no passphrase):
Once this is done, you will see two new files in the
id_test (private key) and
id_test.pub (public key). The
.pub extension refers to public.
Now that you have a key pair, you will need to change the authentication method of the remote server. The way to do this is to copy the content of your public key, inside the
authorized_keys file located on the server. There are basically two means of doing this, either using the
ssh-copy-id utility, or connecting by ssh (with password) and pasting the content of
$ ssh-copy-id -i .ssh/id_test.pub user@server
$ ssh root@server $ vim .ssh/authorized_keys
If you want to configure the rights of the
$ chmod 700 $HOME/.ssh $ chmod go-w $HOME $HOME/.ssh $ chmod 600 $HOME/.ssh/authorized_keys $ chown `whoami` $HOME/.ssh/authorized_keys
Now to make sure your key is loaded in your
ssh-agent use the command
ssh-add -l. If you want the reload the agent
eval $(ssh-agent) > /dev/null and add a new key
You can try to login using the following
Note : to connect to a specific
user, you need to add the public key in
/home/user/.ssh/authorized_keys, the following command automatically selects the base directory of the user specified, for example paul :
$ ssh-copy-id -i .ssh/id_test.pub paul@server
If you managed to connect without any password being asked, you can update the ssh deamon configuration file to add some more security.
$ sudo vim /etc/ssh/sshd_config
# change XXXX between 1000 and 65000 Port XXXX # hightly insecure to let distant root login enabled PermitRootLogin no AuthorizedKeysFile .ssh/authorized_keys # disable password authentication PasswordAuthentication no ChallengeResponseAuthentication no # block port forwarding if not used AllowTcpForwarding no X11Forwarding no # select which users can use with ssh # also possible for groups (see man sshd) AllowUsers paul