← All posts

SSH. Key-Based Authentication

Illustration of SSH public-key authentication

If you’re tired of entering a username and password when connecting over SSH, or your application doesn’t support entering a username and password for SSH but you still need to connect, then you simply need to use key-based authentication!

To do this, you need to set up keys on the client and server: the client will have the private key, and the public key will be stored on the server.

Client-Side Setup

Create and/or edit the file “~/.ssh/config”:


Host example
    User username
    Hostname example.com
    Port 22
    IdentityFile ~/.ssh/username_example

Where:

  • “Host example” — the host name you will specify when connecting over SSH (example: “ssh example”);
  • “User username” — your username on the server;
  • “Hostname example.com” — your server’s hostname (unlike Host, this is the actual server name, not just a name for the connection);
  • “Port 22” — the SSH port;
  • “IdentityFile ~/.ssh/username_example” — the file containing the public key.

Generating Keys and Transferring Them to the Server

Next, let’s generate the keys.
Then we’ll immediately send the public key to the server and rename the private key to “~/.ssh/username_example”:


ssh-keygen
scp ~/.ssh/id_rsa.pub username@example.com:~/.ssh/authorized_keys
mv ~/.ssh/id_rsa ~/.ssh/username_example
chmod -R 600 ~/.ssh
chmod 700 ~/.ssh

It should now connect using the key:


ssh example

If not, leave a comment :)

The ssh-copy-id Utility

There’s also a faster (fewer steps) and more correct (it appends the key to “~/.ssh/authorized_keys” on the server, rather than overwriting it as “scp” does) way to transfer the public key to the server: the ssh-copy-id utility.

That is, instead of:


ssh-keygen
scp ~/.ssh/id_rsa.pub username@example.com:~/.ssh/authorized_keys

use this:


ssh-keygen
ssh-copy-id -i username@example.com

If your port differs from the default (22), for example 2424, you can do this:

ssh-copy-id -i '-p 2424 username@example.com'

Well, that’s it. See also:
WordPress. Updating the Core and Plugins over SSH
Initial Security Measures in FreeBSD
FreeBSD. Passwordless SSH Access Using Encrypted Keys
FreeBSD. DenyHosts Will Protect You from SSH Brute-Force Attacks

Comments are closed. Read the original discussion in Russian →