Difference between revisions of "SSH keys"

From ArchWiki
Jump to: navigation, search
(Add section on using ssh_pam)
m (Background: typo)
(22 intermediate revisions by one other user not shown)
Line 2: Line 2:
 
{{i18n|Using SSH Keys}}
 
{{i18n|Using SSH Keys}}
  
SSH keys are an implementation of [[Wikipedia:Public-key cryptography|public-key cryptography]]. They solve the problem of brute-force password attacks by making them computationally impractical. Additionally, by using SSH keys, you can easily connect to a server, or multiple servers, without having to enter your password for each system.
+
SSH keys serve as a means of identifying yourself to an SSH server using [[Wikipedia:Public-key cryptography|public-key cryptography]] and [[Wikipedia:Challenge-response authentication|challenge-response authentication]]. One immediate advantange this method has over traditional password authentication is that you can be authenticated by the server without ever having to send your password over the network.  Anyone eavesdropping on your connection will not be able to intercept and crack your password because it is never actually transmitted.  Additionally, Using SSH keys for authentication virtually eliminates the risk posed by brute-force password attacks by drastically reducing the chances of the attacker correctly guessing the proper credentials.
  
It is possible to setup your keys without a passphrase, however that is unwise as if anyone gets hold of your key they can use it. This guide describes how to setup your system so that a passphrase is used to encrypt the private key and must be entered to use it.
+
As well as offering additional security, SSH key authentication can be more covenient than the more traditional password authentication. When used with a program known as an SSH agent, SSH keys can allow you to connect to a server, or multiple servers, without having to remember or enter your password for each system.
  
==Generating SSH Keys==
+
SSH keys are not without their drawbacks and may not be appropriate for all environments, but in many circumstances they can offer some strong advantages.  A general understanding of how SSH keys work will help you decide how and when to use them to meet your needs.  This article assumes you already have a basic understanding of the [[Secure Shell]] protocol and have installed the {{Pkg|openssh}} package, available in the [[Official Repositories]].
First you must [[pacman|install]] the {{Pkg|openssh}} package, available from the [[official repositories]].
+
  
The keys can then be generated by running the ssh-keygen command as a user:
+
==Background==
 +
SSH keys always come in pairs, one private and the other public.  The private key is known only to you and it should be safely guarded.  By contrast, the public key can be shared freely with any SSH server to which you would like to connect.
 +
 
 +
When an SSH server has your public key on file and sees you requesting a connection, it uses your public key to construct and send you a challenge.  This challenge is like a coded message and it must be met with the appropriate response before the server will grant you access.  What makes this coded message remarkable is that it can only be understood by someone with the private key.  While the public key can be used to encrypt the message, it cannot be used to decrypt that very same message.  Only you, the holder of the private key, will be able correctly understand the challenge and produce the correct response.
 +
 
 +
This challenge-response phase happens behind the scenes and is invisible to the user.  So as long you hold the private key, which is typically stored in the {{ic|~/.ssh/}} directory, your SSH client should be able to reply with the appropriate response to the server.
 +
 
 +
Because private keys contain sensitive information they are often stored on disk in an encrypted form.  In this case, when the private key is required, a passphrase must first be entered in order to decrypt it.  While this might superficially appear the same as entering a login password on the SSH server, it is only used to decrypt the private key on the local system.  This passphrase is not, and should not, be transmitted over the network.
 +
 
 +
==Generating an SSH key pair==
 +
An SSH key pair can be generated by running the {{ic|ssh-keygen}} command:
 
{{hc|1=
 
{{hc|1=
 
$ ssh-keygen -b 521 -t ecdsa -C"$(id -un)@$(hostname)-$(date --rfc-3339=date)"|2= Generating public/private ecdsa key pair.
 
$ ssh-keygen -b 521 -t ecdsa -C"$(id -un)@$(hostname)-$(date --rfc-3339=date)"|2= Generating public/private ecdsa key pair.
Line 20: Line 29:
 
3a:43:37:6d:e2:5b:97:e2:6f:e2:80:f9:23:97:70:0c mith@middleearth}}
 
3a:43:37:6d:e2:5b:97:e2:6f:e2:80:f9:23:97:70:0c mith@middleearth}}
  
It will prompt you for a location (which you should leave as the default), however the passphrase is the important bit! You should already be aware of the criteria that make a good passphrase.
+
In the above example, {{ic|ssh-keygen}} generates a 521 bit long ({{ic|-b 521}}) public/private ECDSA ({{ic|-t ecdsa}}) key pair with an extended comment including the data ({{ic|-C"$(id -un)"@$(hostname)-$(date --rfc-3339=date)}}).
  
So what did we just do? We generated a 521 bit long ({{ic|-b 521}}) public/private ECDSA ({{ic|-t ecdsa}}) key pair with an extended comment including the data ({{ic|-C"$(id -un)"@$(hostname)-$(date --rfc-3339=date)}}) via the {{ic|ssh-keygen}} command.
+
===Choosing the type of encryption===
 +
The Elliptic Curve Digital Signature Algorithm (ECDSA) provides smaller key sizes and faster operations for equivalent estimated security to the previous methods.  It was introduced as the preferred algorithm for authentication in OpenSSH 5.7, see [http://openssh.org/txt/release-5.7 OpenSSH 5.7 Release Notes].  ECDSA keys might not be compatible with systems that ship old versions of OpenSSH.
  
{{Note| These keys are used only to authenticate you, choosing stronger keys will not increase CPU load when transfering data over SSH.}}
+
If you choose to create an RSA (2048-4096 bit) or DSA (1024 bit) key pair instead of ECDSA, use the {{ic|-t rsa}} or {{ic|-t dsa}} switches in your {{ic|ssh-keygen}} command and do not forget to increase the key size. Running {{ic|ssh-keygen}} without the ({{ic|-b}}) switch should provide reasonable defaults.
  
Elliptic curve cryptography provides smaller key sizes and faster operations for equivalent estimated security. It was introduced as the preferred method for authentication in OpenSSH 5.7, see [http://openssh.org/txt/release-5.7 OpenSSH 5.7 Release Notes]. ECDSA keys might not be compatible with systems that ship old versions of OpenSSH.
+
{{Note|These keys are used only to authenticate you, choosing stronger keys will not increase CPU load when transferring data over SSH.}}
  
If you want to create a RSA (2048-4096 bit) or DSA (1024 bit) key pair instead of ECDSA just use {{ic|-t rsa}} or {{ic|-t dsa}} and do not forget to increase the key size, running {{ic|ssh-keygen}} without  ({{ic|-b}}) will usually provide reasonable defaults.
+
===Choosing the key location and passphrase===
 +
Upon issuing the {{ic|ssh-keygen}} command, you will be prompted for the desired name an location of your private key.  By default, keys are stored in the {{ic|~/.src/}} directory and named according the type of encryption used.  You are advised to accept the default name and location.
 +
 
 +
When prompted for a passphrase, choose something that will be hard to guess if you have the security of your private key in mind.  A longer, more random password will generally be stronger and harder to crack should it fall into the wrong hands.
 +
 
 +
It is also possible to create your private without a passphrase. While this can be convenient, you need to be aware of the associated risks.  Without a passphrase, your private key will be stored on disk in an unencrypted form.  Anyone who gains access to your private key file will then be able to assume your identity on any SSH server to which you connect using key-based authentication.  Furthermore, without a passphrase, you must also trust the root user, as he can bypass file permissions and will be able to access your unencrypted private key file at any time.
  
 
==Copying the public key to the remote server==
 
==Copying the public key to the remote server==
Now you have generated the keys you need to copy the public key (*.pub) to the remote server.  (The private key is kept on the machine from which you want to connect.)
+
Once you have generated a key pair, you will need to copy the public key to the remote server so that it will use SSH key authentication.  The public key file shares the same name as the private key except that is appended with a {{ic|.pub}} extension.  Note that the private key is not shared and remains on the local machine.
 +
 
 
===Simple method===
 
===Simple method===
{{Note|If you are using Terminal on a Mac, you will need to [http://phildawson.tumblr.com/post/484798267/ssh-copy-id-in-mac-os-x add ssh-copy-id] before proceeding.}}
+
If your key file is {{ic|~/.ssh/id_rsa.pub}} you can simply enter the following command.
If your key file is named {{ic|id_rsa.pub}} you can simply do
+
 
  $ ssh-copy-id your-server.org
 
  $ ssh-copy-id your-server.org
or if you need to use different user name
+
 
 +
If your username differs on remote machine, be sure to prepend the username followed by {{ic|@}} to the server name.
 
  $ ssh-copy-id your-login@your-server.org
 
  $ ssh-copy-id your-login@your-server.org
If your key filename is different you will get an error saying "/usr/bin/ssh-copy-id: ERROR: No identities found". In this case you have to provide the location of the identity:
+
 
 +
If your public key filename is anything other than the default of {{ic|~/.ssh/id_rsa.pub}} you will get an error stating {{ic|/usr/bin/ssh-copy-id: ERROR: No identities found}}. In this case, you must explicitly provide the location of the public key.
 
  $ ssh-copy-id -i ~/.ssh/id_ecdsa.pub your-login@your-server.org
 
  $ ssh-copy-id -i ~/.ssh/id_ecdsa.pub your-login@your-server.org
If you need to specify a port, include it within the host declaration:
+
 
 +
If the ssh server is listening on a port other than default of 22, be sure to include it within the host argument.
 
  $ ssh-copy-id -i ~/.ssh/id_rsa.pub '-p 221 username@host'
 
  $ ssh-copy-id -i ~/.ssh/id_rsa.pub '-p 221 username@host'
  
 
===Traditional method===
 
===Traditional method===
By default, for OpenSSH, the public key needs to be concatenated into {{ic|~/.ssh/authorized_keys}}.
+
By default, for OpenSSH, the public key needs to be concatenated with {{ic|~/.ssh/authorized_keys}}.  Begin by copying the public key to the remote server.
  
 
  $ scp ~/.ssh/id_ecdsa.pub mith@metawire.org:
 
  $ scp ~/.ssh/id_ecdsa.pub mith@metawire.org:
  
This copies the public key ({{ic|id_dsa.pub}}) to your remote server via {{ic|scp}} (note the {{ic|:}} at the end of the server address). The file ends up in the home directory, but you can specify another path if you like.
+
The above example copies the public key ({{ic|id_ecdsa.pub}}) to your home directory on the remote server via {{ic|scp}}.  Do not forget to include the {{ic|:}} at the end of the server address. Also note that the name of your public key may differ from the example given.
  
Next up, on the remote server, you need to create the {{ic|~/.ssh}} directory if it does not exist and concatenate the key {{ic|authorized_keys}} file:
+
On the remote server, you will need to create the {{ic|~/.ssh}} directory if it does not yet exist and append your public key to the {{ic|authorized_keys}} file.
  
 
  $ ssh mith@metawire.org
 
  $ ssh mith@metawire.org
Line 59: Line 77:
 
  $ chmod 600 ~/.ssh/authorized_keys
 
  $ chmod 600 ~/.ssh/authorized_keys
  
The last two commands remove the public key from the server (which is not needed now), and sets the correct permissions on the authorized_keys file.
+
The last two commands remove the public key file from the server and set the permissions on the {{ic|authorized_keys}} file such that it is only readable and writable by you, the owner.
  
If you now disconnect from the server, and attempt to reconnect, you should be asked for the passphrase of the key:
+
Disconnect from the server and then attempt to reconnect.  You should now be asked for the passphrase of the key.
  
 
  $ ssh mith@metawire.org
 
  $ ssh mith@metawire.org
Line 68: Line 86:
 
If you are unable to login with the key, double check the permissions on the {{ic|authorized_keys}} file.
 
If you are unable to login with the key, double check the permissions on the {{ic|authorized_keys}} file.
  
Also check the permissions on the {{ic|~/.ssh}} directory, which should have write permissions off for 'group' and 'other'. Run the following command to disable 'group' and 'other' write permissions for the {{ic|~/.ssh}} directory:
+
Also check the permissions on the {{ic|~/.ssh}} directory, which should have write permissions off for 'group' and 'other'. Run the following command to disable 'group' and 'other' write permissions for the {{ic|~/.ssh}} directory.
 
  $ chmod go-w ~/.ssh
 
  $ chmod go-w ~/.ssh
  
 
==Disabling password logins==
 
==Disabling password logins==
Setting up SSH keys is not enough to gain any security benefit. You must also disable password logins:
+
While copying your public key to the remote SSH server eliminates the need to transmit your password over the network, it does not give any added protection against a brute-force password attack.  In the absense of a private key, the SSH server will fall back to password authentication by default, thus allowing a malicious user to attempt to gain access by guessing your password. To disable this behavior, edit the following lines in the {{ic|/etc/ssh/sshd_config}} file on the remote server.
  
 
{{hc|/etc/ssh/sshd_config|
 
{{hc|/etc/ssh/sshd_config|
Line 78: Line 96:
 
ChallengeResponseAuthentication no}}
 
ChallengeResponseAuthentication no}}
  
==Remember key passphrases==
+
==SSH agents==
Now you can login to your servers by using a key instead of a password, but how is this any easier, as you still need to enter the key passphrase? The answer is to use a SSH agent, a program which remembers the passphrases of your keys! There a number of different tools available, so have a read through and choose the one which seems best for you.
+
If your private key is encrypted with a passphrase, this passphrase must be entered every time you attempt to connect to an SSH server using public-key authentication.  Each individual invocation of {{ic|ssh}} or {{ic|scp}} will need the passphrase in order to decrypt your private key before authentication can proceed.
 +
 
 +
An SSH agent is a program which caches your decrypted private keys and provides them to SSH client programs on your behalf.  In this arrangement, you must only provide your passphrase once, when adding your private key to the agent's cache.  This facility can be of great convenience when making frequent SSH connections.
 +
 
 +
An agent is typically configured run automatically upon login and persist for the duration of your login session.  A number of different solutions exist to achieve this effect and you should explore a few of them before deciding which one best suits your needs.
  
 
===ssh-agent===
 
===ssh-agent===
Line 161: Line 183:
 
Finally, open a new shell or close your current shell and open it again. If it is your first run keychain will prompt you for the passphrase of the specified private key.
 
Finally, open a new shell or close your current shell and open it again. If it is your first run keychain will prompt you for the passphrase of the specified private key.
  
'''Alternate method'''
+
=====Alternate startup method=====
 
+
There are numerous ways in which keychain can be invoked and you are encouraged to experiment to find a method that works for you.  An alternative implementation of a keychain startup script is as follows.
 
{{hc|/etc/profile.d/keychain.sh|<nowiki>
 
{{hc|/etc/profile.d/keychain.sh|<nowiki>
 
/usr/bin/keychain -Q -q --nogui ~/.ssh/id_dsa
 
/usr/bin/keychain -Q -q --nogui ~/.ssh/id_dsa
Line 176: Line 198:
 
After installing these, closing your Xsession and relogging you will henceforth be asked your passphrase on Xsession init without any further work.
 
After installing these, closing your Xsession and relogging you will henceforth be asked your passphrase on Xsession init without any further work.
  
====Using the pam_ssh Pluggable Authentication Module====
+
====Using pam_ssh====
The [http://pam-ssh.sourceforge.net/ pam_ssh] project exists to provide a Pluggable Authentication Module (PAM) for SSH private keys.  This module can provide single sign-on behavior for your SSH connections.  On login, your SSH private key passphrase can be entered in place of, or in addition to, your traditional system password.  Once you have been authenticated, the pam_ssh module spawns ssh-agent to store your decrypted private key for the duration of the session.
+
The [http://pam-ssh.sourceforge.net/ pam_ssh] project exists to provide a [[Wikipedia:Pluggable authentication module|Pluggable Authentication Module]] (PAM) for SSH private keys.  This module can provide single sign-on behavior for your SSH connections.  On login, your SSH private key passphrase can be entered in place of, or in addition to, your traditional system password.  Once you have been authenticated, the pam_ssh module spawns ssh-agent to store your decrypted private key for the duration of the session.
  
 
To enable single sign-on behavior at the tty login prompt, install the unofficial {{AUR|pam_ssh}} package, available in the [[Arch User Repository]].  
 
To enable single sign-on behavior at the tty login prompt, install the unofficial {{AUR|pam_ssh}} package, available in the [[Arch User Repository]].  
  
Edit the {{ic|/etc/pam.d/login}} file to add the lines highlighted in bold in the example below.  The order in which these lines appear is significiant and can affect login behavior.
+
Edit the {{ic|/etc/pam.d/login}} configuration file to include the lines highlighted in bold in the example below.  The order in which these lines appear is significiant and can affect login behavior.
  
 
{{Warning|Misconfiguring PAM can leave the system in a state where all users become locked out.  Before making any changes, you should have an understanding of how PAM configuration works as well as a backup means of accessing the PAM configuration files, such as an Arch Live CD, in case you become locked out and need to revert any changes.  An IBM developerWorks [http://www.ibm.com/developerworks/linux/library/l-pam/index.html article] is available which explains PAM configuration in further detail.}}
 
{{Warning|Misconfiguring PAM can leave the system in a state where all users become locked out.  Before making any changes, you should have an understanding of how PAM configuration works as well as a backup means of accessing the PAM configuration files, such as an Arch Live CD, in case you become locked out and need to revert any changes.  An IBM developerWorks [http://www.ibm.com/developerworks/linux/library/l-pam/index.html article] is available which explains PAM configuration in further detail.}}
Line 211: Line 233:
 
}}
 
}}
  
In the above example, the login program uses pam_ssh to check the password against the user's SSH private key passphrase.  If the password matches, the user is immediately granted access to the system.  If the password does not match, it is handed to the pam_unix module which provides traditional password authentication by checking {{ic|/etc/passwd}}.  In this way, ssh_pam will be transparent to users without an SSH private key.
+
In the above example, login uses pam_ssh to check the entered password against the user's SSH private key passphrase.  If the password matches, the user is immediately granted access to the system.  If the password does not match, control falls to the pam_unix module which provides traditional password authentication by checking the entered password against the {{ic|/etc/passwd}} file.  In this way, ssh_pam will be transparent to users without an SSH private key.
  
If you use a another means of logging in such as an X11 display manager, you must edit it's respective PAM configuration file located under {{ic|/etc/pam.d/}} in a similar fashion.
+
If you use a another means of logging in, such as an X11 display manager like SLiM or XDM and you would like it to provide similar functionality, you must edit its associated PAM configuration file in a similar fashion.  Packages providing support for PAM typically place a default configuration file in the {{ic|/etc/pam.d/}} directory.
  
Further details on using pam_ssh are available in the pam_ssh man page.
+
Further details on how to use pam_ssh and a list of its options can be found in the pam_ssh man page.
  
=====Known issues with ssh_pam=====
+
=====Known issues with pam_ssh=====
Work on the pam_ssh project is infrequent and you should be aware of some of its limitations.
+
Work on the pam_ssh project is infrequent and the documentation provided is sparse.  You should be aware of some of its limitations which are not mentioned in the package itself.
  
 
* SSH keys employing the newer option of ECDSA (elliptic curve) cryptography do not appear to be supported by pam_ssh.  You must use either RSA or DSA keys.
 
* SSH keys employing the newer option of ECDSA (elliptic curve) cryptography do not appear to be supported by pam_ssh.  You must use either RSA or DSA keys.

Revision as of 22:40, 19 December 2011

This template has only maintenance purposes. For linking to local translations please use interlanguage links, see Help:i18n#Interlanguage links.


Local languages: Català – Dansk – English – Español – Esperanto – Hrvatski – Indonesia – Italiano – Lietuviškai – Magyar – Nederlands – Norsk Bokmål – Polski – Português – Slovenský – Česky – Ελληνικά – Български – Русский – Српски – Українська – עברית – العربية – ไทย – 日本語 – 正體中文 – 简体中文 – 한국어


External languages (all articles in these languages should be moved to the external wiki): Deutsch – Français – Română – Suomi – Svenska – Tiếng Việt – Türkçe – فارسی

SSH keys serve as a means of identifying yourself to an SSH server using public-key cryptography and challenge-response authentication. One immediate advantange this method has over traditional password authentication is that you can be authenticated by the server without ever having to send your password over the network. Anyone eavesdropping on your connection will not be able to intercept and crack your password because it is never actually transmitted. Additionally, Using SSH keys for authentication virtually eliminates the risk posed by brute-force password attacks by drastically reducing the chances of the attacker correctly guessing the proper credentials.

As well as offering additional security, SSH key authentication can be more covenient than the more traditional password authentication. When used with a program known as an SSH agent, SSH keys can allow you to connect to a server, or multiple servers, without having to remember or enter your password for each system.

SSH keys are not without their drawbacks and may not be appropriate for all environments, but in many circumstances they can offer some strong advantages. A general understanding of how SSH keys work will help you decide how and when to use them to meet your needs. This article assumes you already have a basic understanding of the Secure Shell protocol and have installed the openssh package, available in the Official Repositories.

Background

SSH keys always come in pairs, one private and the other public. The private key is known only to you and it should be safely guarded. By contrast, the public key can be shared freely with any SSH server to which you would like to connect.

When an SSH server has your public key on file and sees you requesting a connection, it uses your public key to construct and send you a challenge. This challenge is like a coded message and it must be met with the appropriate response before the server will grant you access. What makes this coded message remarkable is that it can only be understood by someone with the private key. While the public key can be used to encrypt the message, it cannot be used to decrypt that very same message. Only you, the holder of the private key, will be able correctly understand the challenge and produce the correct response.

This challenge-response phase happens behind the scenes and is invisible to the user. So as long you hold the private key, which is typically stored in the ~/.ssh/ directory, your SSH client should be able to reply with the appropriate response to the server.

Because private keys contain sensitive information they are often stored on disk in an encrypted form. In this case, when the private key is required, a passphrase must first be entered in order to decrypt it. While this might superficially appear the same as entering a login password on the SSH server, it is only used to decrypt the private key on the local system. This passphrase is not, and should not, be transmitted over the network.

Generating an SSH key pair

An SSH key pair can be generated by running the ssh-keygen command:

$ ssh-keygen -b 521 -t ecdsa -C"$(id -un)@$(hostname)-$(date --rfc-3339=date)"
Generating public/private ecdsa key pair.
Enter file in which to save the key (/home/mith/.ssh/id_ecdsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/mith/.ssh/id_ecdsa.
Your public key has been saved in /home/mith/.ssh/id_ecdsa.pub.
The key fingerprint is:
3a:43:37:6d:e2:5b:97:e2:6f:e2:80:f9:23:97:70:0c mith@middleearth

In the above example, ssh-keygen generates a 521 bit long (-b 521) public/private ECDSA (-t ecdsa) key pair with an extended comment including the data (-C"$(id -un)"@$(hostname)-$(date --rfc-3339=date)).

Choosing the type of encryption

The Elliptic Curve Digital Signature Algorithm (ECDSA) provides smaller key sizes and faster operations for equivalent estimated security to the previous methods. It was introduced as the preferred algorithm for authentication in OpenSSH 5.7, see OpenSSH 5.7 Release Notes. ECDSA keys might not be compatible with systems that ship old versions of OpenSSH.

If you choose to create an RSA (2048-4096 bit) or DSA (1024 bit) key pair instead of ECDSA, use the -t rsa or -t dsa switches in your ssh-keygen command and do not forget to increase the key size. Running ssh-keygen without the (-b) switch should provide reasonable defaults.

Note: These keys are used only to authenticate you, choosing stronger keys will not increase CPU load when transferring data over SSH.

Choosing the key location and passphrase

Upon issuing the ssh-keygen command, you will be prompted for the desired name an location of your private key. By default, keys are stored in the ~/.src/ directory and named according the type of encryption used. You are advised to accept the default name and location.

When prompted for a passphrase, choose something that will be hard to guess if you have the security of your private key in mind. A longer, more random password will generally be stronger and harder to crack should it fall into the wrong hands.

It is also possible to create your private without a passphrase. While this can be convenient, you need to be aware of the associated risks. Without a passphrase, your private key will be stored on disk in an unencrypted form. Anyone who gains access to your private key file will then be able to assume your identity on any SSH server to which you connect using key-based authentication. Furthermore, without a passphrase, you must also trust the root user, as he can bypass file permissions and will be able to access your unencrypted private key file at any time.

Copying the public key to the remote server

Once you have generated a key pair, you will need to copy the public key to the remote server so that it will use SSH key authentication. The public key file shares the same name as the private key except that is appended with a .pub extension. Note that the private key is not shared and remains on the local machine.

Simple method

If your key file is ~/.ssh/id_rsa.pub you can simply enter the following command.

$ ssh-copy-id your-server.org

If your username differs on remote machine, be sure to prepend the username followed by @ to the server name.

$ ssh-copy-id your-login@your-server.org

If your public key filename is anything other than the default of ~/.ssh/id_rsa.pub you will get an error stating /usr/bin/ssh-copy-id: ERROR: No identities found. In this case, you must explicitly provide the location of the public key.

$ ssh-copy-id -i ~/.ssh/id_ecdsa.pub your-login@your-server.org

If the ssh server is listening on a port other than default of 22, be sure to include it within the host argument.

$ ssh-copy-id -i ~/.ssh/id_rsa.pub '-p 221 username@host'

Traditional method

By default, for OpenSSH, the public key needs to be concatenated with ~/.ssh/authorized_keys. Begin by copying the public key to the remote server.

$ scp ~/.ssh/id_ecdsa.pub mith@metawire.org:

The above example copies the public key (id_ecdsa.pub) to your home directory on the remote server via scp. Do not forget to include the : at the end of the server address. Also note that the name of your public key may differ from the example given.

On the remote server, you will need to create the ~/.ssh directory if it does not yet exist and append your public key to the authorized_keys file.

$ ssh mith@metawire.org
mith@metawire.org's password:
$ mkdir ~/.ssh
$ cat ~/id_ecdsa.pub >> ~/.ssh/authorized_keys
$ rm ~/id_ecdsa.pub
$ chmod 600 ~/.ssh/authorized_keys

The last two commands remove the public key file from the server and set the permissions on the authorized_keys file such that it is only readable and writable by you, the owner.

Disconnect from the server and then attempt to reconnect. You should now be asked for the passphrase of the key.

$ ssh mith@metawire.org
Enter passphrase for key '/home/mith/.ssh/id_ecdsa':

If you are unable to login with the key, double check the permissions on the authorized_keys file.

Also check the permissions on the ~/.ssh directory, which should have write permissions off for 'group' and 'other'. Run the following command to disable 'group' and 'other' write permissions for the ~/.ssh directory.

$ chmod go-w ~/.ssh

Disabling password logins

While copying your public key to the remote SSH server eliminates the need to transmit your password over the network, it does not give any added protection against a brute-force password attack. In the absense of a private key, the SSH server will fall back to password authentication by default, thus allowing a malicious user to attempt to gain access by guessing your password. To disable this behavior, edit the following lines in the /etc/ssh/sshd_config file on the remote server.

/etc/ssh/sshd_config
PasswordAuthentication no
ChallengeResponseAuthentication no

SSH agents

If your private key is encrypted with a passphrase, this passphrase must be entered every time you attempt to connect to an SSH server using public-key authentication. Each individual invocation of ssh or scp will need the passphrase in order to decrypt your private key before authentication can proceed.

An SSH agent is a program which caches your decrypted private keys and provides them to SSH client programs on your behalf. In this arrangement, you must only provide your passphrase once, when adding your private key to the agent's cache. This facility can be of great convenience when making frequent SSH connections.

An agent is typically configured run automatically upon login and persist for the duration of your login session. A number of different solutions exist to achieve this effect and you should explore a few of them before deciding which one best suits your needs.

ssh-agent

ssh-agent is the default agent included with OpenSSH.

$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-vEGjCM2147/agent.2147; export SSH_AUTH_SOCK;
SSH_AGENT_PID=2148; export SSH_AGENT_PID;
echo Agent pid 2148;

When you run ssh-agent, it will print out what environment variables it would use. To make use of these variables, run the command through the eval command.

$ eval `ssh-agent`
Agent pid 2157

You can add this to /etc/profile so that it will be run whenever you open a session:

# echo 'eval `ssh-agent`' >> /etc/profile

Note the correct quotes: the outer ones are single quotes, where as the inner ones are backticks.

Now that the ssh-agent is running, we need to tell it that we have a private key and where that is.

$ ssh-add ~/.ssh/id_ecdsa
Enter passphrase for /home/user/.ssh/id_ecdsa:
Identity added: /home/user/.ssh/id_ecdsa (/home/user/.ssh/id_ecdsa)

When asked for the passphrase, enter it. Now you can login to your remote server without having to enter your password while your private key is password-protected.

The only downside is that a new instance of ssh-agent needs to be created for every new console (shell) you open, that means you have to run ssh-add every time again on each console. There is a workaround to that with a program or rather a script called keychain which is covered in the next section.

Using GnuPG Agent

The GnuPG agent, distributed with the gnupg2 package, has OpenSSH agent emulation. If you use GPG you might consider using its agent to take care of all of your keys. Otherwise you might like the PIN entry dialog it provides and its passphrase management, which is different from keychain.

To start using GPG agent for your SSH keys you should first start the gpg-agent with the --enable-ssh-support option. Example (don't forget to make the file executable):

/etc/profile.d/gpg-agent.sh
#!/bin/sh

# Start the GnuPG agent and enable OpenSSH agent emulation
gnupginf="${HOME}/.gnupg/gpg-agent.info"

if pgrep -u "${USER}" gpg-agent >/dev/null 2>&1; then
    eval `cat $gnupginf`
    eval `cut -d= -f1 $gnupginf | xargs echo export`
else
    eval `gpg-agent --enable-ssh-support --daemon`
fi

Once gpg-agent is running you can use ssh-add to approve keys, just like you did with plain ssh-agent. The list of approved keys is stored in the ~/.gnupg/sshcontrol file. Once your key is approved you will get a PIN entry dialog every time your passphrase is needed. You can control passphrase caching in the ~/.gnupg/gpg-agent.conf file. The following example would have gpg-agent cache your keys for 3 hours:

 # Cache settings
 default-cache-ttl 10800
 default-cache-ttl-ssh 10800

Other useful settings for this file include the PIN entry program (GTK, QT or ncurses version), keyboard grabbing and so on...:

 # Environment file
 write-env-file /home/username/.gnupg/gpg-agent.info
 
 # Keyboard control
 #no-grab
   
 # PIN entry program
 #pinentry-program /usr/bin/pinentry-curses
 #pinentry-program /usr/bin/pinentry-qt4
 pinentry-program /usr/bin/pinentry-gtk-2

Using keychain

Keychain manages one or more specified private keys. When initialized it will ask for the passphrase for the private key(s) and store it. That way your private key is password protected but you will not have to enter your password over and over again.

Install the keychain package, available from the official repositories.

Append the following command to your .bashrc, .bash_profile, or create /etc/profile.d/keychain.sh as root and make it executable (e.g. chmod 755 keychain.sh):

eval `keychain --eval --agents ssh --nogui -Q -q id_dsa`

Adding the -q or --quiet flag to the keychain command will suppress the output to new sessions. Also note that the --agents flag is not strictly necessary, because keychain will build the list automatically based on the existence of ssh-agent or gpg-agent on the system. If you want greater security replace -Q with --clear but will be less convenient.

If necessary, replace ~/.ssh/id_dsa with the path to your private key. For those using a non-Bash compatible shell, see keychain --help or man keychain for details on other shells.

Finally, open a new shell or close your current shell and open it again. If it is your first run keychain will prompt you for the passphrase of the specified private key.

Alternate startup method

There are numerous ways in which keychain can be invoked and you are encouraged to experiment to find a method that works for you. An alternative implementation of a keychain startup script is as follows.

/etc/profile.d/keychain.sh
/usr/bin/keychain -Q -q --nogui ~/.ssh/id_dsa
[[ -f $HOME/.keychain/$HOSTNAME-sh ]] && source $HOME/.keychain/$HOSTNAME-sh

Using ssh-agent and x11-ssh-askpass

You need to start the ssh-agent everytime you start a new Xsession. The ssh-agent will be closed when the X session ends.

Install a variant of x11-ssh-askpass which will ask your passphrase everytime you open a new Xsession. Either use the original x11-ssh-askpass, go with ksshaskpass (depends on kdelibs) or with openssh-askpass (depends on qt), all available from the official repositories.

After installing these, closing your Xsession and relogging you will henceforth be asked your passphrase on Xsession init without any further work.

Using pam_ssh

The pam_ssh project exists to provide a Pluggable Authentication Module (PAM) for SSH private keys. This module can provide single sign-on behavior for your SSH connections. On login, your SSH private key passphrase can be entered in place of, or in addition to, your traditional system password. Once you have been authenticated, the pam_ssh module spawns ssh-agent to store your decrypted private key for the duration of the session.

To enable single sign-on behavior at the tty login prompt, install the unofficial pam_sshAUR package, available in the Arch User Repository.

Edit the /etc/pam.d/login configuration file to include the lines highlighted in bold in the example below. The order in which these lines appear is significiant and can affect login behavior.

Warning: Misconfiguring PAM can leave the system in a state where all users become locked out. Before making any changes, you should have an understanding of how PAM configuration works as well as a backup means of accessing the PAM configuration files, such as an Arch Live CD, in case you become locked out and need to revert any changes. An IBM developerWorks article is available which explains PAM configuration in further detail.

Template:File

In the above example, login uses pam_ssh to check the entered password against the user's SSH private key passphrase. If the password matches, the user is immediately granted access to the system. If the password does not match, control falls to the pam_unix module which provides traditional password authentication by checking the entered password against the /etc/passwd file. In this way, ssh_pam will be transparent to users without an SSH private key.

If you use a another means of logging in, such as an X11 display manager like SLiM or XDM and you would like it to provide similar functionality, you must edit its associated PAM configuration file in a similar fashion. Packages providing support for PAM typically place a default configuration file in the /etc/pam.d/ directory.

Further details on how to use pam_ssh and a list of its options can be found in the pam_ssh man page.

Known issues with pam_ssh

Work on the pam_ssh project is infrequent and the documentation provided is sparse. You should be aware of some of its limitations which are not mentioned in the package itself.

  • SSH keys employing the newer option of ECDSA (elliptic curve) cryptography do not appear to be supported by pam_ssh. You must use either RSA or DSA keys.
  • The ssh-agent process spawned by pam_ssh does not persist between user logins. If you like to keep a gnu screen session active between logins you may notice when reattaching to your screen session that it can no longer communicate with ssh-agent. This is due to the fact that the gnu screen environment and those of its children will still reference the instance of ssh-agent which existed when gnu screen was invoked but was subsequently killed in a previous logout. The alternative keychain method avoids this problem by keeping the ssh-agent process alive between logins.

GNOME Keyring

If you use the GNOME desktop, the GNOME Keyring tool can be used as an SSH agent. Visit the GNOME Keyring article.

Troubleshooting

If it appears that the SSH server is ignoring your keys, ensure that you have the proper permissions set on all relevant files.

For the local machine:

$ chmod 700 ~/
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/id_ecdsa

For the remote machine:

$ chmod 700 ~/
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys

Failing this, run the sshd in debug mode and monitor the output while connecting:

# /usr/sbin/sshd -d

See also