Difference between revisions of "SSH keys"

From ArchWiki
Jump to: navigation, search
m (Reorganization (it was unclear for a newbie) + update for systemd)
(Update OpenSSH6.5 release date)
 
(285 intermediate revisions by 90 users not shown)
Line 1: Line 1:
 
[[Category:Secure Shell]]
 
[[Category:Secure Shell]]
[[es:SSH Keys]]
+
[[es:SSH keys]]
[[it:SSH Keys]]
+
[[it:SSH keys]]
[[ru:SSH Keys]]
+
[[ja:SSH 鍵]]
[[sr:SSH Keys]]
+
[[ru:SSH keys]]
[[tr:SSH_Anahtarları]]
+
[[sr:SSH keys]]
[[zh-CN:SSH Keys]]
+
[[tr:SSH Anahtarları]]
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.
+
[[zh-cn:SSH keys]]
 +
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 advantage 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 convenient 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.
 
As well as offering additional security, SSH key authentication can be more convenient 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 {{Pkg|openssh}} package, available in the [[Official Repositories]].
+
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.   
  
==Background==
+
This article assumes you already have a basic understanding of the [[Secure Shell]] protocol and have [[Install|installed]] the {{Pkg|openssh}} package.
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 particularly secure 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 to correctly understand the challenge and produce the correct response.
+
== Background ==
 +
 
 +
SSH keys are always generated in pairs with one known as the private key and the other as the public key.  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 wish to connect.
 +
 
 +
If 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 an encrypted message and it must be met with the appropriate response before the server will grant you access.  What makes this coded message particularly secure is that it can only be understood by the private key holder.  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 to correctly understand the challenge and produce the proper response.
  
 
This challenge-response phase happens behind the scenes and is invisible to the user.  As long as 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.
 
This challenge-response phase happens behind the scenes and is invisible to the user.  As long as 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 are considered 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.
+
A private key is a guarded secret and as such it is advisable to store it on disk in an encrypted form.  When the encrypted private key is required, a passphrase must first be entered in order to decrypt it.  While this might superficially appear as though you are providing a login password to the SSH server, the passphrase is only used to decrypt the private key on the local system.  The passphrase is not transmitted over the network.
  
==Generating an SSH key pair==
+
== Generating an SSH key pair ==
An SSH key pair can be generated by running the {{ic|ssh-keygen}} command:
+
 
 +
An SSH key pair can be generated by running the {{ic|ssh-keygen}} command, defaulting to 2048-bit RSA (and SHA256) which the {{man|1|ssh-keygen}} man page says is "''generally considered sufficient''" and should be compatible with virtually all clients and servers:
  
 
{{hc
 
{{hc
|$ ssh-keygen -t ecdsa -b 521 -C "$(whoami)@$(hostname)-$(date -I)"
+
|$ ssh-keygen
|<nowiki>Generating public/private ecdsa key pair.
+
|<nowiki>Generating public/private rsa key pair.
Enter file in which to save the key (/home/username/.ssh/id_ecdsa):
+
Enter file in which to save the key (/home/<username>/.ssh/id_rsa):
 +
Enter passphrase (empty for no passphrase):
 +
Enter same passphrase again:
 +
Your identification has been saved in /home/<username>/.ssh/id_rsa.
 +
Your public key has been saved in /home/<username>/.ssh/id_rsa.pub.
 +
The key fingerprint is:
 +
SHA256:gGJtSsV8BM+7w018d39Ji57F8iO6c0N2GZq3/RY2NhI username@hostname
 +
The key's randomart image is:
 +
+---[RSA 2048]----+
 +
|  ooo.          |
 +
|  oo+.          |
 +
|  + +.+          |
 +
| o +  +    E . |
 +
|  .  . S . . =.o|
 +
|    . + . . B+@o|
 +
|      + .  oo*=O|
 +
|      .  ..+=o+|
 +
|          o=ooo+|
 +
+----[SHA256]-----+</nowiki>}}
 +
 
 +
The [http://www.cs.berkeley.edu/~dawnsong/papers/randomart.pdf randomart image] was [http://www.openssh.com/txt/release-5.1 introduced in OpenSSH 5.1] as an easier means of visually identifying the key fingerprint.
 +
 
 +
You can also add an optional comment field to the public key with the {{ic|-C}} switch, to more easily identify it in places such as {{ic|~/.ssh/known_hosts}}, {{ic|~/.ssh/authorized_keys}} and {{ic|ssh-add -L}} output. For example:
 +
 
 +
$ ssh-keygen -C "$(whoami)@$(hostname)-$(date -I)"
 +
 
 +
will add a comment saying which user created the key on which machine and when.
 +
 
 +
The {{ic|-o}} switch can also be used to save the private key in the new OpenSSH format, which has increased resistance to brute-force password cracking (but is not supported by versions of OpenSSH prior to 6.5 [https://lwn.net/Articles/583485/ released 2014-01-29]). Use the {{ic|-a}} switch to specify the number of KDF rounds. According to {{man|1|ssh-keygen}}, Ed25519 keys always use the new private key format.
 +
 
 +
=== Choosing the type of encryption ===
 +
 
 +
OpenSSH supports several key exchange algorithms which can be divided in two groups depending on the mathematical properties they exploit:
 +
 
 +
# [[Wikipedia:Digital_Signature_Algorithm|DSA]] and [[Wikipedia:RSA_(cryptosystem)|RSA]], which rely on the [[wikipedia:Integer_factorization#Difficulty_and_complexity|practical difficulty]] of factoring the product of two large prime numbers,
 +
# [[Wikipedia:Elliptic_Curve_Digital_Signature_Algorithm|ECDSA]] and [[Wikipedia:Curve25519|Ed25519]], which rely on the elliptic curve  [[Wikipedia:Discrete_logarithm|discrete logarithm]] problem. ([https://www.certicom.com/index.php/52-the-elliptic-curve-discrete-logarithm-problem example])
 +
 
 +
[https://blog.cloudflare.com/a-relatively-easy-to-understand-primer-on-elliptic-curve-cryptography/ Elliptic curve cryptography] (ECC) algorithms are a [[Wikipedia:Elliptic_curve_cryptography#History|more recent addition]] to public key cryptosystems. One of their main advantages is their ability to provide [[Wikipedia:Elliptic_curve_cryptography#Rationale|the same level of security with smaller keys]], which makes for less computationally intensive operations (''i.e.'' faster key creation, encryption and decryption) and reduced storage and transmission requirements.
 +
 
 +
OpenSSH 7.0 [https://www.archlinux.org/news/openssh-70p1-deprecates-ssh-dss-keys/ deprecated and disabled support for DSA keys] due to discovered vulnerabilities, therefore the choice of [[Wikipedia:cryptosystem|cryptosystem]] lies within RSA or one of the two types of ECC.
 +
 
 +
[[#RSA]] keys will give you the greatest portability, while [[#Ed25519]] will give you the best security but requires recent versions of client & server[https://www.gentoo.org/support/news-items/2015-08-13-openssh-weak-keys.html]. [[#ECDSA]] is likely more compatible than Ed25519 (though still less than RSA), but suspicions exist about its security (see below).
 +
 
 +
{{Note|1=<nowiki></nowiki>
 +
* As of July 10, 2015, [[GNOME Keyring]] does not handle ECDSA[https://bugzilla.gnome.org/show_bug.cgi?id=641082] and Ed25519[https://bugzilla.gnome.org/show_bug.cgi?id=723274] keys. Users will have to turn to other [[#SSH agents|SSH agents]] or stick to RSA keys.
 +
* These keys are used only to authenticate you; choosing stronger keys will not increase CPU load when transferring data over SSH.
 +
}}
 +
 
 +
==== RSA ====
 +
 
 +
{{ic|ssh-keygen}} defaults to RSA therefore there is no need to specify it with the {{ic|-t}} option. It provides the best compatibility of all algorithms but requires the key size to be larger to provide sufficient security.
 +
 
 +
Minimum key size is 1024 bits, default is 2048 (see {{man|1|ssh-keygen}}) and maximum is 16384:
 +
 
 +
{{hc|$ ssh-keygen -b 32768|
 +
key bits exceeds maximum 16384}}
 +
 
 +
If you wish to generate a stronger RSA key pair (''e.g.'' to guard against cutting-edge or unknown attacks and more sophisticated attackers), simply specify the {{ic|-b}} option with a higher bit value than the default:
 +
 
 +
{{hc
 +
|$ ssh-keygen -b 4096
 +
|<nowiki>Generating public/private rsa key pair.
 +
Enter file in which to save the key (/home/<username>/.ssh/id_rsa):
 
Enter passphrase (empty for no passphrase):
 
Enter passphrase (empty for no passphrase):
 
Enter same passphrase again:
 
Enter same passphrase again:
Your identification has been saved in /home/username/.ssh/id_ecdsa.
+
Your identification has been saved in /home/<username>/.ssh/id_rsa.
Your public key has been saved in /home/username/.ssh/id_ecdsa.pub.
+
Your public key has been saved in /home/<username>/.ssh/id_rsa.pub.
 
The key fingerprint is:
 
The key fingerprint is:
dd:15:ee:24:20:14:11:01:b8:72:a2:0f:99:4c:79:7f username@localhost-2011-12-22
+
SHA256:+Pqo84NC+vAQQ9lUV0z+/zPHsyCe8oZpy6hLkIa7qfk <username>@<hostname>
 
The key's randomart image is:
 
The key's randomart image is:
+--[ECDSA  521]---+
+
+---[RSA 4096]----+
|     ..oB=.   . |
+
|   ... .+o      |
|   .   . . . . |
+
| . ..       |
|  .  .      . +  |
+
| o .     .       |
| oo.o   . . =  |
+
|. . . .  .      |
|o+.+.   S . . . |
+
|o. +  . S  .    |
|=.   . E        |
+
| o+ .  .    .   |
| o    .         |
+
|o+  . o. o . |
.             |
+
|.=+ + .oo=..o o+o|
|                 |
+
|+=E..**+oo=+  o*|
+-----------------+</nowiki>}}
+
+----[SHA256]-----+</nowiki>}}
 +
 
 +
Be aware though that there are diminishing returns in using longer keys.[https://security.stackexchange.com/a/25377][https://www.gnupg.org/faq/gnupg-faq.html#no_default_of_rsa4096] The GnuPG FAQ reads: "''If you need more security than RSA-2048 offers, the way to go would be to switch to elliptical curve cryptography — not to continue using RSA''".[https://www.gnupg.org/faq/gnupg-faq.html#please_use_ecc]
 +
 
 +
On the other hand, the latest iteration of the [https://www.nsa.gov/ia/programs/suiteb_cryptography/index.shtml NSA Fact Sheet Suite B Cryptography] suggests a minimum 3072-bit modulus for RSA while "''[preparing] for the upcoming quantum resistant algorithm transition''".[http://www.keylength.com/en/6/]
 +
 
 +
==== ECDSA ====
 +
 
 +
{{Note|The Windows SSH client PuTTY does not support ECDSA as of March 2016. One needs a PuTTY development snapshot to connect to a server that uses only ECDSA keys.[http://www.chiark.greenend.org.uk/~sgtatham/putty/wishlist/]}}
 +
 
 +
The Elliptic Curve Digital Signature Algorithm (ECDSA) was introduced as the preferred algorithm for authentication [http://www.openssh.com/txt/release-5.7 in OpenSSH 5.7]. Some vendors also disable the required implementations due to potential patent issues.
 +
 
 +
There are two sorts of concerns with it:
 +
 
 +
# ''Political concerns'', the trustworthiness of NIST-produced curves [https://crypto.stackexchange.com/questions/10263/should-we-trust-the-nist-recommended-ecc-parameters being questioned] after revelations that the NSA willingly inserts backdoors into softwares, hardware components and published standards were made; well-known cryptographers [https://www.schneier.com/blog/archives/2013/09/the_nsa_is_brea.html#c1675929 have] [http://safecurves.cr.yp.to/rigid.html expressed] [https://www.hyperelliptic.org/tanja/vortraege/20130531.pdf doubts] about how the NIST curves were designed, and voluntary tainting has already [https://www.schneier.com/blog/archives/2007/11/the_strange_sto.html been] [http://www.scientificamerican.com/article/nsa-nist-encryption-scandal/ proved] in the past.
 +
# ''Technical concerns'', about the [http://blog.cr.yp.to/20140323-ecdsa.html difficulty to properly implement the standard] and the [http://www.gossamer-threads.com/lists/openssh/dev/57162#57162 slowness and design flaws] which reduce security in insufficiently precautious implementations.
 +
 
 +
Both of those concerns are best summarized in [https://git.libssh.org/projects/libssh.git/tree/doc/curve25519-sha256@libssh.org.txt#n4 libssh curve25519 introduction]. Although the political concerns are still subject to debate, there is a [https://news.ycombinator.com/item?id=7597653 clear consensus] that [[#Ed25519]] is technically superior and should therefore be preferred.
 +
 
 +
==== Ed25519 ====
 +
 
 +
[http://ed25519.cr.yp.to/ Ed25519] was introduced in [http://www.openssh.com/txt/release-6.5 OpenSSH 6.5]: "''Ed25519 is an elliptic curve signature scheme that offers better security than ECDSA and DSA and good performance''". Its main strengths are its speed, its constant-time run time (and resistance against side-channel attacks), and its lack of nebulous hard-coded constants.[https://git.libssh.org/projects/libssh.git/tree/doc/curve25519-sha256@libssh.org.txt] See also [https://blog.mozilla.org/warner/2011/11/29/ed25519-keys/ this blog post] by a Mozilla developer on how it works.
 +
 
 +
It is already implemented in [[Wikipedia:Curve25519#Popularity|many applications and libraries]] and is the [https://www.libssh.org/2013/11/03/openssh-introduces-curve25519-sha256libssh-org-key-exchange/ default key exchange algorithm] (which is different from key ''signature'') in OpenSSH.
 +
 
 +
Ed25519 key pairs can be generated with:
  
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 "$(whoami)@$(hostname)-$(date -I)"}}).  The [http://www.cs.berkeley.edu/~dawnsong/papers/randomart.pdf randomart image] was introduced in OpenSSH 5.1 as an easier means of visually identifying the key fingerprint.
+
$ ssh-keygen -t ed25519
  
===Choosing the type of encryption===
+
There is no need to set the key size, as all Ed25519 keys are 256 bits. Also, they rely on a [http://www.gossamer-threads.com/lists/openssh/dev/57162#57162 new key format] which "''uses a bcrypt-based key derivation function that makes brute-force attacks against stolen private keys far slower''".
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.''' Some vendors also disable the required implementations due to potential patent issues.
+
  
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.
+
For those reasons, compatibility with older versions of OpenSSH or [[Ssh#Other_SSH_clients_and_servers|other SSH clients and servers]] may prove troublesome.
  
{{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 ===
  
===Choosing the key location and passphrase===
+
Upon issuing the {{ic|ssh-keygen}} command, you will be prompted for the desired name and location of your private key.  By default, keys are stored in the {{ic|~/.ssh/}} directory and named according to the type of encryption used.  You are advised to accept the default name and location in order for later code examples in this article to work properly.
Upon issuing the {{ic|ssh-keygen}} command, you will be prompted for the desired name and location of your private key.  By default, keys are stored in the {{ic|~/.ssh/}} directory and named according the type of encryption used.  You are advised to accept the default name and location in order for later code examples in this article to work properly.
+
  
 
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.
 
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.
Line 63: Line 153:
 
It is also possible to create your private key 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.
 
It is also possible to create your private key 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.
  
====Changing the private key's passphrase without changing the key====
+
==== Changing the private key's passphrase without changing the key ====
 
If the originally chosen SSH key passphrase is undesirable or must be changed, one can use the {{ic|ssh-keygen}} command to change the passphrase without changing the actual key.
 
If the originally chosen SSH key passphrase is undesirable or must be changed, one can use the {{ic|ssh-keygen}} command to change the passphrase without changing the actual key.
  
 
To change the passphrase for the private RSA key, run the following command:
 
To change the passphrase for the private RSA key, run the following command:
 
  $ ssh-keygen -f ~/.ssh/id_rsa -p
 
  $ ssh-keygen -f ~/.ssh/id_rsa -p
 +
 +
==== Managing multiple keys ====
 +
 +
It is possible —although [http://security.stackexchange.com/questions/10963/whats-the-common-pragmatic-strategy-for-managing-key-pairs not considered best practice]— to use the same SSH key pair for multiple hosts.
 +
 +
On the other hand, it is rather easy to maintain distinct keys for multiple hosts by using the {{ic|IdentityFile}} directive in your openSSH config file:
 +
 +
{{hc|~/.ssh/config|
 +
Host SERVER1
 +
  IdentitiesOnly yes
 +
  IdentityFile ~/.ssh/id_rsa_SERVER1
 +
 +
Host SERVER2
 +
  IdentitiesOnly yes
 +
  IdentityFile ~/.ssh/id_ed25519_SERVER2
 +
}}
 +
 +
See {{man|5|ssh_config}} for full description of these options.
  
 
==Copying the public key to the remote server==
 
==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 it is appended with a {{ic|.pub}} extension.  Note that the private key is not shared and remains on the local machine.
 
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 it 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|1=This method might fail if the remote server uses a non-{{ic|sh}} shell such as {{ic|tcsh}} as default and uses OpenSSH older than 6.6.1p1. See [https://bugzilla.redhat.com/show_bug.cgi?id=1045191 this bug report].}}
 +
 
 
If your key file is {{ic|~/.ssh/id_rsa.pub}} you can simply enter the following command.
 
If your key file is {{ic|~/.ssh/id_rsa.pub}} you can simply enter the following command.
 +
 
  $ ssh-copy-id remote-server.org
 
  $ ssh-copy-id remote-server.org
  
 
If your username differs on remote machine, be sure to prepend the username followed by {{ic|@}} to the server name.
 
If your username differs on remote machine, be sure to prepend the username followed by {{ic|@}} to the server name.
 +
 
  $ ssh-copy-id username@remote-server.org
 
  $ ssh-copy-id username@remote-server.org
  
 
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.
 
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 username@remote-server.org
+
 
 +
  $ ssh-copy-id -i ~/.ssh/id_ed25519.pub username@remote-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.
 
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@remote-server.org'
 
  
===Traditional method===
+
$ ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 221 username@remote-server.org
 +
 
 +
=== Manual method ===
 +
 
 
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.
 
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.
  
Line 97: Line 213:
 
  username@remote-server.org's password:
 
  username@remote-server.org's password:
 
  $ mkdir ~/.ssh
 
  $ mkdir ~/.ssh
 +
$ chmod 700 ~/.ssh
 
  $ cat ~/id_ecdsa.pub >> ~/.ssh/authorized_keys
 
  $ cat ~/id_ecdsa.pub >> ~/.ssh/authorized_keys
 
  $ rm ~/id_ecdsa.pub
 
  $ rm ~/id_ecdsa.pub
Line 103: Line 220:
 
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.
 
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.
  
==Security==
+
== SSH agents ==
  
===Securing the authorized_keys file===
+
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.
  
To add further protection level, you can prevent users adding new public keys and connecting from them. To achieve this goal, you simply need to restrict access to the user's {{ic|authorized_keys}} file in such a way that it can <u>only</u> be modified <u>only</u> by root.
+
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.
  
Optional: To avoid such an heavy work for all of your users, you can set up an centralized keys management. Create a directory, say, {{ic|/etc/ssh/user-keys}}, owned by root, and put users' keys in files named according to their usernames (e.g. {{ic|/etc/ssh/user-keys/john}}). Keep the files root-owned as well.
+
An agent is typically configured to run automatically upon login and persist for the duration of your login session. A variety of agents, front-ends, and configurations exist to achieve this effect. This section provides an overview of a number of different solutions which can be adapted to meet your specific needs.
  
Then change the {{ic|AuthorizedKeysFile}} option in {{ic|/etc/ssh/sshd_config}} to point to your new directory:
+
=== ssh-agent ===
  
{{hc|/etc/ssh/sshd_config|
+
{{ic|ssh-agent}} is the default agent included with OpenSSH.  It can be used directly or serve as the back-end to a few of the front-end solutions mentioned later in this section.  When {{ic|ssh-agent}} is run, it forks to background and prints necessary environment variables. E.g.
AuthorizedKeysFile /etc/ssh/user-keys/%u}}
+
  
{{ic|%u}} will be expanded to the user's name when authenticating. The ssh daemon may need to be reloaded {{ic|systemctl reload sshd}}.
+
{{hc|$ ssh-agent|2=
 +
SSH_AUTH_SOCK=/tmp/ssh-vEGjCM2147/agent.2147; export SSH_AUTH_SOCK;
 +
SSH_AGENT_PID=2148; export SSH_AGENT_PID;
 +
echo Agent pid 2148;
 +
}}
  
{{Note|If you copy the {{ic|authorized_keys}} file from another location, make sure the permissions are set to 600. Run {{ic|chmod 600 /etc/ssh/user-keys/john}} to ensure this.}}
+
To make use of these variables, run the command through the {{ic|eval}} command.
  
===Disabling password logins===
+
{{hc|$ eval $(ssh-agent)|
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 absence 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.
+
Agent pid 2157
 +
}}
  
{{hc|/etc/ssh/sshd_config|
+
Once {{ic|ssh-agent}} is running, you will need to add your private key to its cache:
PasswordAuthentication no
+
ChallengeResponseAuthentication no}}
+
  
==SSH agents==
+
{{hc|$ ssh-add ~/.ssh/id_ecdsa|
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.
+
Enter passphrase for /home/user/.ssh/id_ecdsa:
 +
Identity added: /home/user/.ssh/id_ecdsa (/home/user/.ssh/id_ecdsa)
 +
}}
  
An SSH agent is a program which caches your decrypted private keys and provides them to SSH client programs on your behalfIn 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.
+
If your private key is encrypted, {{ic|ssh-add}} will prompt you to enter your passphraseOnce your private key has been successfully added to the agent you will be able to make SSH connections without having to enter your passphrase.
  
An agent is typically configured to run automatically upon login and persist for the duration of your login session. A variety of agents, front-ends, and configurations exist to achieve this effect.  This section provides an overview of a number of different solutions which can be adapted to meet your specific needs.
+
{{Tip|To make all {{ic|ssh}} clients, including {{ic|git}} store keys in the agent on first use, add the configuration setting {{ic|AddKeysToAgent yes}} to {{ic|~/.ssh/config}}. Other possible values are {{ic|confirm}}, {{ic|ask}} and {{ic|no}} (default).}}
  
===ssh-agent===
+
In order to start the agent automatically and make sure that only one {{ic|ssh-agent}} process runs at a time, add the following to your {{ic|~/.bashrc}}:
ssh-agent is the default agent included with OpenSSH.  It can be used directly or serve as the back-end to a few of the front-end solutions mentioned later in this section.  When {{ic|ssh-agent}} is run, it will fork itself to the background and print out the environment variables it would use.
+
  
$ ssh-agent
+
{{bc|<nowiki>
SSH_AUTH_SOCK=/tmp/ssh-vEGjCM2147/agent.2147; export SSH_AUTH_SOCK;
+
if ! pgrep -u $USER ssh-agent > /dev/null; then
SSH_AGENT_PID=2148; export SSH_AGENT_PID;
+
    ssh-agent > ~/.ssh-agent-thing
echo Agent pid 2148;
+
fi
 +
if [[ "$SSH_AGENT_PID" == "" ]]; then
 +
    eval $(<~/.ssh-agent-thing)
 +
fi
 +
</nowiki>}}
  
To make use of these variables, run the command through the {{ic|eval}} command.
+
This will run a {{ic|ssh-agent}} process if there is not one already, and save the output thereof. If there is one running already, we retrieve the cached {{ic|ssh-agent}} output and evaluate it which will set the necessary environment variables.
  
$ eval $(ssh-agent)
+
There also exist a number of front-ends to {{ic|ssh-agent}} and alternative agents described later in this section which avoid this problem.
Agent pid 2157
+
  
You can append the above command to your {{ic|~/.bash_profile}} script so that it will run automatically when starting a login shell.
+
==== Start ssh-agent with systemd user ====
+
$ echo 'eval $(ssh-agent)' >> ~/.bash_profile
+
  
If you would rather have ssh-agent run automatically for all users append the command to {{ic|/etc/profile}} instead.
+
It is possible to use the [[systemd/User]] facilities to start the agent.
  
# echo 'eval $(ssh-agent)' >> /etc/profile
+
{{hc|~/.config/systemd/user/ssh-agent.service|<nowiki>
 +
[Unit]
 +
Description=SSH key agent
  
Once {{ic|ssh-agent}} is running, you will need to add your private key to its cache.
+
[Service]
 +
Type=forking
 +
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket
 +
ExecStart=/usr/bin/ssh-agent -a $SSH_AUTH_SOCK
  
$ ssh-add ~/.ssh/id_ecdsa
+
[Install]
Enter passphrase for /home/user/.ssh/id_ecdsa:
+
WantedBy=</nowiki>''default''.target
Identity added: /home/user/.ssh/id_ecdsa (/home/user/.ssh/id_ecdsa)
+
}}
  
If you would like your private keys to be added automatically on login. Append the following command to your {{ic|~/.bash_profile}} as well.
+
Add {{ic|1=export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/ssh-agent.socket"}} to your shell's startup file, for example {{ic|.bash_profile}} for [[Bash]]. Then [[enable]] or [[start]] the service.
  
$ echo 'ssh-add' >> ~/.bash_profile
+
==== ssh-agent as a wrapper program ====
  
If your private key is encrypted {{ic|ssh-add}} will prompt you to enter your passphrase.  Once your private key has been successfully added to the agent you will be able to make SSH connections without having to enter a passphrase.
+
An alternative way to start ssh-agent (with, say, each X session) is described in [http://upc.lbl.gov/docs/user/sshagent.shtml this ssh-agent tutorial by UC Berkeley Labs]. A basic use case is if you normally begin X with the {{ic|startx}} command, you can instead prefix it with {{ic|ssh-agent}} like so:
  
One downside to this approach is that a new instance of {{ic|ssh-agent}} is created for every login shell and each instance will persist between login sessions. Over time you can wind up with dozens of needless {{ic|ssh-agent}} processes running.  There exist a number of front-ends to ssh-agent and alternative agents described later in this section which avoid this problem.
+
  $ ssh-agent startx
  
===GnuPG Agent===
+
And so you do not even need to think about it you can put an alias in your {{ic|.bash_aliases}} file or equivalent:
  
{{Note|The stock gnupg Arch Linux package does not support ECC encryption and signing. Hence you cannot use the GnuPG agent to manage ECDSA keys.}}
+
  alias startx='ssh-agent startx'
  
The [[GnuPG]] agent, distributed with the {{Pkg|gnupg}} package, available in the [[Official Repositories|official repositories]], 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.
+
Doing it this way avoids the problem of having extraneous {{ic|ssh-agent}} instances floating around between login sessions. Exactly one instance will live and die with the entire X session.
  
To start using GPG agent for your SSH keys you should first start the gpg-agent with the {{ic|--enable-ssh-support}} option. Example (do not forget to make the file executable):
+
{{note|You can also add {{ic|eval $(ssh-agent)}} to {{ic|~/.xinitrc}}.}}
{{hc|/etc/profile.d/gpg-agent.sh|<nowiki>
+
#!/bin/sh
+
  
# Start the GnuPG agent and enable OpenSSH agent emulation
+
See [[#Calling x11-ssh-askpass with ssh-add|the below notes on using x11-ssh-askpass with ssh-add]] for an idea on how to immediately add your key to the agent.
gnupginf="${HOME}/.gpg-agent-info"
+
  
if pgrep -u "${USER}" gpg-agent >/dev/null 2>&1; then
+
=== GnuPG Agent ===
    eval `cat $gnupginf`
+
    eval `cut -d= -f1 $gnupginf | xargs echo export`
+
else
+
    eval `gpg-agent -s --enable-ssh-support --daemon`
+
fi
+
</nowiki>}}
+
  
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 {{ic|~/.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 {{ic|~/.gnupg/gpg-agent.conf}} file. The following example would have gpg-agent cache your keys for 3 hours:
+
The [[GnuPG#gpg-agent|gpg-agent]] has OpenSSH agent emulation. See [[GnuPG#SSH agent]] for necessary configuration.
{{hc|~/.gnupg/gpg-agent.conf|
+
  # 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...:
+
  
{{Note|gpg-agent.conf must be created and the variable 'write-env-file' must be set in order to allow gpg-agent keys to be injected to SSH across logins. (Unless you restart the gpg-agent, and therefore export its settings, with every login.)}}
+
=== Keychain ===
{{hc|~/.gnupg/gpg-agent.conf|<nowiki>
+
  # Environment file
+
  write-env-file /home/username/.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-kwallet
+
  pinentry-program /usr/bin/pinentry-gtk-2
+
  
</nowiki>}}
+
[http://www.funtoo.org/Keychain Keychain] is a program designed to help you easily manage your SSH keys with minimal user interaction. It is implemented as a shell script which drives both ''ssh-agent'' and ''ssh-add''. A notable feature of Keychain is that it can maintain a single ''ssh-agent'' process across multiple login sessions. This means that you only need to enter your passphrase once each time your local machine is booted.
  
===Keychain===
+
==== Installation ====
[http://www.funtoo.org/wiki/Keychain Keychain] is a program designed to help you easily manage your SSH keys with minimal user interaction.  It is implemented as a shell script which drives both {{ic|ssh-agent}} and {{ic|ssh-add}}.  A notable feature of Keychain is that it can maintain a single {{ic|ssh-agent}} process across multiple login sessions.  This means that you only need to enter your passphrase once each time your local machine is booted.
+
  
[[pacman|Install]] the {{Pkg|keychain}} package, available from the [[Official Repositories]].
+
[[Install]] the {{Pkg|keychain}} package available from the [[official repositories]].
  
Append the following line to {{ic|~/.bash_profile}}, or create {{ic|/etc/profile.d/keychain.sh}} as root and make it executable (e.g. {{ic|chmod 755 keychain.sh}}):
+
==== Configuration ====
{{hc|~/.bash_profile|
+
 
eval $(keychain --eval --agents ssh -Q --quiet id_ecdsa)
+
{{Warning|As of 2015-09-26, the {{ic|-Q, --quick}} option has the unexpected side-effect of making ''keychain'' switch to a newly-spawned ''ssh-agent'' upon relogin (at least on systems using [[GNOME]]), forcing you to re-add all the previously registered keys.}}
 +
 
 +
Add a line similar to the following to your [[shell]] configuration file, ''e.g.'' if using [[Bash]]:
 +
 
 +
{{hc|~/.bashrc|
 +
eval $(keychain --eval --quiet id_ed25519 id_rsa ~/.keys/my_custom_key)
 
}}
 
}}
  
In the above example, the {{ic|--eval}} switch outputs lines to be evaluated by the opening {{ic|eval}} command.  This sets the necessary environments variables for SSH client to be able to find your agent.  The {{ic|--agents}} switch is not strictly necessary, because Keychain will build the list automatically based on the existence of ssh-agent or gpg-agent on the system. Adding the {{ic|--quiet}} switch will limit output to warnings, errors, and user prompts.  If you want greater security replace {{ic|-Q}} with {{ic|--clear}} but will be less convenient.
+
{{Note|{{ic|~/.bashrc}} is used instead of the upstream suggested {{ic|~/.bash_profile}} because on Arch it is sourced by both login and non-login shells, making it suitable for textual and graphical environments alike. See [[Bash#Invocation]] for more information on the difference between those.}}
  
If necessary, replace {{ic|~/.ssh/id_ecdsa}} with the path to your private key. For those using a non-Bash compatible shell, see {{ic|keychain --help}} or {{ic|man keychain}} for details on other shells.
+
In the above example,
 +
* the {{ic|--eval}} switch outputs lines to be evaluated by the opening {{ic|eval}} command; this sets the necessary environments variables for SSH client to be able to find your agent.
 +
* {{ic|--quiet}} will limit output to warnings, errors, and user prompts.
  
To test Keychain, log out from your session and log back in. If this is your first time running Keychain, it will prompt you for the passphrase of the specified private key.  Because Keychain reuses the same {{ic|ssh-agent}} process on successive logins, you shouldn't have to enter your passphrase the next time you log in. You will only ever be prompted for your passphrase once each time the machine is rebooted.
+
Multiple keys can be specified on the command line, as shown in the example. By default keychain will look for key pairs in the {{ic|~/.ssh/}} directory, but absolute path can be used for keys in non-standard location. You may also use the {{ic|--confhost}} option to inform keychain to look in {{ic|~/.ssh/config}} for {{ic|IdentityFile}} settings defined for particular hosts, and use these paths to locate keys.
  
====Alternate startup methods====
+
See {{ic|keychain --help}} or {{ic|man keychain}} for details on setting ''keychain'' for other shells.
There are numerous ways in which Keychain can be invoked and you are encouraged to experiment to find a method that works for you.  The {{ic|keychain}} command itself comes with dozens of command-line options which are described in the Keychain man page.
+
  
One alternative implementation of a Keychain startup script could be to create the file {{ic|/etc/profile.d/keychain.sh}} as the root user and add the following lines.
+
To test Keychain, simply open a new terminal emulator or log out and back in your session. It should prompt you for the passphrase of the specified private key(s) (if applicable), either using the program set in {{ic|$SSH_ASKPASS}} or on the terminal.
  
{{hc|/etc/profile.d/keychain.sh|<nowiki>
+
Because Keychain reuses the same ''ssh-agent'' process on successive logins, you should not have to enter your passphrase the next time you log in or open a new terminal. You will only be prompted for your passphrase once each time the machine is rebooted.
/usr/bin/keychain -Q -q --nogui ~/.ssh/id_ecdsa
+
[[ -f $HOME/.keychain/$HOSTNAME-sh ]] && source $HOME/.keychain/$HOSTNAME-sh
+
</nowiki>}}
+
  
Be sure to also make {{ic|/etc/profile.d/keychain.sh}} executable by changing its file permissions.
+
==== Tips ====
# chmod 755 /etc/profile.d/keychain.sh
+
  
If you do not want to get asked for your passphrase every time you login but rather the first time you actually attempt to connect, you may add the following to your {{ic|.bashrc}}:
+
* ''keychain'' expects public key files to exist in the same directory as their private counterparts, with a {{ic|.pub}} extension. If the private key is a symlink, the public key can be found alongside the symlink or in the same directory as the symlink target (this capability requires the {{ic|readlink}} command to be available on the system).
alias ssh='eval $(/usr/bin/keychain --eval --agents ssh -Q --quiet .ssh/id_rsa) && ssh'
+
This will ask you if you try to use ssh for the first time. Remember however that this will ONLY ask you if {{ic|.bashrc}} is applicable. So you would always have your first ssh-command to be executed in a terminal.
+
  
===x11-ssh-askpass===
+
*to disable the graphical prompt and always enter your passphrase on the terminal, use the {{ic|--nogui}} option. This allows to copy-paste long passphrases from a password manager for example.
The x11-ssh-askpass package provides a graphical dialog for entering your passhrase when running an X session.  x11-ssh-askpass depends only the {{Pkg|libx11}} and {{Pkg|libxt}} libraries, and the appearance of x11-ssh-askpass is customizable.  While it can be invoked by the {{ic|ssh-add}} program which will then load your decrypted keys into [[#ssh-agent|ssh-agent]], the following instructions will instead configure x11-ssh-askpass to be invoked by the aforementioned [[#Keychain|Keychain]] script.
+
  
Install {{Pkg|keychain}} and {{Pkg|x11-ssh-askpass}}, both available in the [[Official Repositories]].
+
*if you do not want to be immediately prompted for unlocking the keys but rather wait until they are needed, use the {{ic|--noask}} option.
  
Edit your {{ic|~/.xinitrc}} file to include the lines highlighted in bold, replacing the name and location of your private if necessary. Be sure to place these commands '''before''' the line which invokes your window mananger.
+
{{Note|Keychain is able to manage [[GPG]] keys in the same fashion. By default it attempts to start ''ssh-agent'' only, but you can modify this behavior using the {{ic|--agents}} option, ''e.g.'' {{ic|--agents ssh,gpg}}. See {{ic|man keychain}}.}}
 +
 
 +
=== envoy ===
 +
 
 +
An alternative to keychain is [https://github.com/vodik/envoy envoy]. Envoy is available as {{Pkg|envoy}} , or the Git version as {{AUR|envoy-git}}.
 +
 
 +
After installing it, set up the envoy socket by [[enabling]] {{ic|envoy@ssh-agent.socket}}.
 +
 
 +
And add to your shell's rc file:
 +
 
 +
envoy -t ssh-agent -a ''ssh_key''
 +
source <(envoy -p)
 +
 
 +
If this syntax for sourcing causes errors (in mksh, for example), you can replace it with:
 +
 
 +
envoy -t ssh-agent -a ''ssh_key''
 +
eval "$(envoy -p)"
 +
 
 +
If the key is {{ic|~/.ssh/id_rsa}}, {{ic|~/.ssh/id_dsa}}, {{ic|~/.ssh/id_ecdsa}}, or {{ic|~/.ssh/identity}}, the {{ic|-a ''ssh_key''}} parameter is not needed.
 +
 
 +
==== envoy with key passphrases stored in kwallet ====
 +
 
 +
If you have long passphrases for your SSH keys, remembering them can be a pain. So let us tell kwallet to store them!
 +
Along with {{Pkg|envoy}}, install {{Pkg|ksshaskpass}} and {{Pkg|kwalletmanager}} from the [[official repositories]]. Next, enable the envoy socket in systemd (see above).
 +
 
 +
{{Note|1=As of April 30, 2015, if after installation {{Pkg|ksshaskpass}} keeps asking for access to your wallet even after having submitted the password, you might have [https://bbs.archlinux.org/viewtopic.php?id=192862 this] problem. The proposed solution is to install {{Aur|ksshaskpass4}}, though this might break your login.}}
 +
 
 +
First, you will add this script to {{ic|~/.kde4/Autostart/ssh-agent.sh}}:
 +
 
 +
#!/bin/sh
 +
envoy -t ssh-agent -a ''ssh_key''
 +
 
 +
Then, make sure the script is executable by running: {{ic|chmod +x ~/.kde4/Autostart/ssh-agent.sh}}
 +
 
 +
And add this to {{ic|~/.kde4/env/ssh-agent.sh}}:
 +
 
 +
#!/bin/sh
 +
eval $(envoy -p)
 +
 
 +
When you log into KDE, it will execute the {{ic|ssh-agent.sh}} script. This will call ''ksshaskpass'', which will prompt you for your kwallet password when envoy calls ''ssh-agent''.
 +
 
 +
=== x11-ssh-askpass ===
 +
 
 +
The {{pkg|x11-ssh-askpass}} package provides a graphical dialog for entering your passhrase when running an X session. ''x11-ssh-askpass'' depends only on the {{Pkg|libx11}} and {{Pkg|libxt}} libraries, and the appearance of ''x11-ssh-askpass'' is customizable. While it can be invoked by the ''ssh-add'' program, which will then load your decrypted keys into [[#ssh-agent|ssh-agent]], the following instructions will, instead, configure ''x11-ssh-askpass'' to be invoked by the aforementioned [[#Keychain|Keychain]] script.
 +
 
 +
Install {{Pkg|keychain}} and {{Pkg|x11-ssh-askpass}}, both available in the [[official repositories]].
 +
 
 +
Edit your {{ic|~/.xinitrc}} file to include the following lines, replacing the name and location of your private key if necessary. Be sure to place these commands '''before''' the line which invokes your window manager.
  
 
{{hc|~/.xinitrc|
 
{{hc|~/.xinitrc|
'''keychain ~/.ssh/id_ecdsa'''
+
keychain ~/.ssh/id_ecdsa
'''[ -f ~/.keychain/$HOSTNAME-sh ] && . ~/.keychain/$HOSTNAME-sh 2>/dev/null'''
+
[ -f ~/.keychain/$HOSTNAME-sh ] && . ~/.keychain/$HOSTNAME-sh 2>/dev/null
'''[ -f ~/.keychain/$HOSTNAME-sh-gpg ] && . ~/.keychain/$HOSTNAME-sh-gpg 2>/dev/null'''
+
[ -f ~/.keychain/$HOSTNAME-sh-gpg ] && . ~/.keychain/$HOSTNAME-sh-gpg 2>/dev/null
 
...
 
...
 
exec openbox-session}}
 
exec openbox-session}}
  
In the above example, the first line invokes {{ic|keychain}} and passes the name and location of your private key. If this is not the first time keychain was invoked, the following two lines load the contents of {{ic|$HOSTNAME-sh}} and {{ic|$HOSTNAME-sh-gpg}} if they exist. These files store the environment variables of the previous instance of {{ic|keychain}}.
+
In the above example, the first line invokes ''keychain'' and passes the name and location of your private key. If this is not the first time ''keychain'' was invoked, the following two lines load the contents of {{ic|$HOSTNAME-sh}} and {{ic|$HOSTNAME-sh-gpg}}, if they exist. These files store the environment variables of the previous instance of ''keychain''.
 +
 
 +
==== Calling x11-ssh-askpass with ssh-add ====
 +
 
 +
The ''ssh-add'' manual page specifies that, in addition to needing the {{ic|DISPLAY}} variable defined, you also need {{ic|SSH_ASKPASS}} set to the name of your askpass program (in this case ''x11-ssh-askpass''). It bears keeping in mind that the default Arch Linux installation places the ''x11-ssh-askpass'' binary in {{ic|/usr/lib/ssh/}}, which will not be in most people's {{ic|PATH}}. This is a little annoying, not only when declaring the {{ic|SSH_ASKPASS}} variable, but also when theming. You have to specify the full path everywhere. Both inconveniences can be solved simultaneously by symlinking:
 +
 
 +
$ ln -sv /usr/lib/ssh/x11-ssh-askpass ~/bin/ssh-askpass
 +
 
 +
This is assuming that {{ic|~/bin}} is in your {{ic|PATH}}. So now in your {{ic|.xinitrc}}, before calling your window manager, one just needs to export the {{ic|SSH_ASKPASS}} environment variable:
 +
 
 +
$ export SSH_ASKPASS=ssh-askpass
 +
 
 +
and your [[X resources]] will contain something like:
 +
 
 +
ssh-askpass*background: #000000
 +
 
 +
Doing it this way works well with [[#ssh-agent as a wrapper program|the above method on using ''ssh-agent'' as a wrapper program]]. You start X with {{ic|ssh-agent startx}} and then add ''ssh-add'' to your window manager's list of start-up programs.
 +
 
 +
==== Theming ====
 +
 
 +
The appearance of the ''x11-ssh-askpass'' dialog can be customized by setting its associated [[X resources]]. The ''x11-ssh-askpass'' [http://www.jmknoble.net/software/x11-ssh-askpass/ home page]{{Dead link|2015|04|01}} presents some [http://www.jmknoble.net/software/x11-ssh-askpass/screenshots.html example themes]{{Dead link|2015|04|01}}. See the ''x11-ssh-askpass'' manual page for full details.
 +
 
 +
==== Alternative passphrase dialogs ====
 +
 
 +
There are other passphrase dialog programs which can be used instead of ''x11-ssh-askpass''. The following list provides some alternative solutions.
 +
 
 +
* {{Pkg|ksshaskpass}} is available in the official repositories. It is dependent on {{Pkg|kdelibs}} and is suitable for the [[KDE]] Desktop Environment.
 +
 
 +
* {{Pkg|openssh-askpass}} depends on the {{Pkg|qt4}} libraries and is available from the official repositories.
  
====Theming====
+
=== pam_ssh ===
The appearance of the x11-ssh-askpass dialog can be customized by setting its associated [[X resources]].  The x11-ssh-askpass [http://www.jmknoble.net/software/x11-ssh-askpass/ homepage] presents some example [http://www.jmknoble.net/software/x11-ssh-askpass/screenshots.html example themes].  See the x11-ssh-askpass man page for full details.
+
  
====Alternative passphrase dialogs====
+
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 passwordOnce you have been authenticated, the pam_ssh module spawns ssh-agent to store your decrypted private key for the duration of the session.
There are other passphrase dialog programs which can be used instead of x11-ssh-askpassThe following list provides some alternative solutions.
+
  
* {{Pkg|ksshaskpass}} is available in the Official Repositories.  It is dependent on {{Pkg|kdelibs}} and is suitable for the KDE Desktop Environment.
+
To enable single sign-on behavior at the tty login prompt, install the unofficial {{AUR|pam_ssh}} package.  
  
* {{Pkg|openssh-askpass}} depends on the {{Pkg|qt}} libraries, and is available from the Official Repositories.
+
{{Note|pam_ssh 2.0 now requires that all private keys used in the authentication process be located under {{ic|~/.ssh/login-keys.d/}}.}}
  
===pam_ssh===
+
Create a symlink to your private key file and place it in {{ic|~/.ssh/login-keys.d/}}Replace the {{ic|id_rsa}} in the example below with the name of your own private key file.
The [http://pam-ssh.sourceforge.net/ pam_ssh] project exists to provide a [[Wikipedia:Pluggable authentication module|Pluggable Authentication Module]] (PAM) for SSH private keysThis 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]].  
+
$ mkdir ~/.ssh/login-keys.d/
 +
$ cd ~/.ssh/login-keys.d/
 +
$ ln -s ../id_rsa
  
 
Edit the {{ic|/etc/pam.d/login}} configuration file to include the text 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 text highlighted in bold in the example below.  The order in which these lines appear is significiant and can affect login behavior.
Line 287: Line 458:
 
auth      required    pam_securetty.so
 
auth      required    pam_securetty.so
 
auth      requisite    pam_nologin.so
 
auth      requisite    pam_nologin.so
'''auth      sufficient  pam_ssh.so'''
 
 
auth      include      system-local-login
 
auth      include      system-local-login
 +
'''auth      optional    pam_ssh.so        try_first_pass'''
 
account    include      system-local-login
 
account    include      system-local-login
 
session    include      system-local-login
 
session    include      system-local-login
Line 294: Line 465:
 
}}
 
}}
  
{{out of date|The below paragraph has not been properly updated for {{pkg|pambase}}<nowiki>=</nowiki>20120701-1.}}
+
In the above example, login authentication initially proceeds as it normally would, with the user being prompted to enter his user password.  The additional {{ic|auth}} authentication rule added to the end of the authentication stack then instructs the pam_ssh module to try to decrypt any private keys found in the {{ic|~/.ssh/login-keys.d}} directoryThe {{ic|try_first_pass}} option is passed to the pam_ssh module, instructing it to first try to decrypt any SSH private keys using the previously entered user password.  If the user's private key passphrase and user password are the same, this should succeed and the user will not be prompted to enter the same password twice.  In the case where the user's private key passphrase user password differ, the pam_ssh module will prompt the user to enter the SSH passphrase after the user password has been entered.  The {{ic|optional}} control value ensures that users without an SSH private key are still able to log in.  In this way, the use of pam_ssh will be transparent to users without an SSH private key.
 
+
In the above example, login uses the pam_ssh module to check the entered password against the user's SSH private key passphrase.  If the password matches, the user is immediately authenticated and granted access to the systemIf the password does not match, control falls to the pam_unix module included via the {{ic|/etc/pam.d/system-local-login}} file.  The pam_unix module provides traditional system password authentication.  Note, however, that the line which actually calls the pam_unix module resides in {{ic|/etc/pam.d/system-auth}} and this file is referenced in {{ic|/etc/pam.d/login}} through a series of "include" control flagsBecause the pam_unix module is passed the {{ic|try_first_pass}} option, it first checks the previously entered password against the {{ic|/etc/passwd}} file instead of prompting for a password again if the pam_ssh authentication failed.  In this way, the use of pam_ssh will be transparent to users without an SSH private key.
+
  
 
If you use 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.
 
If you use 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.
Line 302: Line 471:
 
Further details on how to use pam_ssh and a list of its options can be found 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 pam_ssh====
+
==== Using a different password to unlock the SSH key ====
 +
 
 +
If you want to unlock the SSH keys or not depending on whether you use your key's passphrase or the (different!) login password, you can modify {{ic|/etc/pam.d/system-auth}} to
 +
 
 +
{{hc|/etc/pam.d/system-auth|2=
 +
#%PAM-1.0
 +
 
 +
'''auth      [success=1 new_authtok_reqd=1 ignore=ignore default=ignore]  pam_unix.so    try_first_pass nullok'''
 +
'''auth      required  pam_ssh.so      use_first_pass'''
 +
auth      optional  pam_permit.so
 +
auth      required  pam_env.so
 +
 
 +
account  required  pam_unix.so
 +
account  optional  pam_permit.so
 +
account  required  pam_time.so
 +
 
 +
password  required  pam_unix.so    try_first_pass nullok sha512 shadow
 +
password  optional  pam_permit.so
 +
 
 +
session  required  pam_limits.so
 +
session  required  pam_unix.so
 +
session  optional  pam_permit.so
 +
'''session  optional  pam_ssh.so'''
 +
}}
 +
 
 +
For an explanation, see [http://unix.stackexchange.com/a/239486/863 here].
 +
 
 +
==== 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.
 
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_sshYou must use either RSA or DSA keys.
+
* Versions of pam_ssh prior to version 2.0 do not support SSH keys employing the newer option of ECDSA (elliptic curve) cryptography.  If you are using earlier versions of pam_ssh you must use either RSA or DSA keys.
 +
 
 +
* The {{ic|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 because 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 [[#Keychain|Keychain]] front-end 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. See the [[GNOME Keyring]] article for further details.
 +
 
 +
=== Store SSH keys with Kwallet ===
 +
 
 +
For instructions on how to use kwallet to store your SSH keys, see [[KDE Wallet#Using the KDE Wallet to store ssh keys]].
 +
 
 +
=== KeePass2 with KeeAgent plugin ===
 +
 
 +
[http://lechnology.com/software/keeagent/ KeeAgent] is a plugin for [[KeePass]] that allows SSH keys stored in a KeePass database to be used for SSH authentication by other programs.
 +
 
 +
* Supports both PuTTY and OpenSSH private key formats.
 +
* Works with native SSH agent on Linux/Mac and with PuTTY on Windows.
 +
 
 +
See [[KeePass#Plugin Installation]] or [[install]] the {{AUR|keepass-plugin-keeagent}} package. There is also the beta version, where new features appear first, {{AUR|keepass-plugin-keeagent-beta}}.
  
* The {{ic|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 because 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 [[#keychain|Keychain]] front-end avoids this problem by keeping the ssh-agent process alive between logins.
+
== Troubleshooting ==
  
===GNOME Keyring===
+
=== Key ignored by the server ===
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.<br />
 
If it appears that the SSH server is ignoring your keys, ensure that you have the proper permissions set on all relevant files.<br />
 
For the local machine:
 
For the local machine:
Line 333: Line 547:
 
Failing this, run the sshd in debug mode and monitor the output while connecting:
 
Failing this, run the sshd in debug mode and monitor the output while connecting:
  
  # /usr/sbin/sshd -d
+
  # /usr/bin/sshd -d
  
=== Using kdm ===
+
== See also ==
It appears that kdm doesn't launch the ssh-agent process directly. You need to install the {{Pkg|kde-agent}}.
+
  
==See also==
+
* [http://www.ibm.com/developerworks/linux/library/l-keyc.html OpenSSH key management, Part 1]
* [http://www-106.ibm.com/developerworks/linux/library/l-keyc.html OpenSSH key management, Part 1]
+
* [http://www.ibm.com/developerworks/linux/library/l-keyc2/ OpenSSH key management, Part 2]
* [http://www-106.ibm.com/developerworks/linux/library/l-keyc2/ OpenSSH key management, Part 2]
+
* [http://www.ibm.com/developerworks/library/l-keyc3/ OpenSSH key management, Part 3]
* [http://www-106.ibm.com/developerworks/library/l-keyc3/ OpenSSH key management, Part 3]
+
 
* [http://kimmo.suominen.com/docs/ssh/ Getting started with SSH]
 
* [http://kimmo.suominen.com/docs/ssh/ Getting started with SSH]
* [http://openssh.org/txt/release-5.7 OpenSSH 5.7 Release Notes]
+
* [http://www.openssh.com/txt/release-5.7 OpenSSH 5.7 Release Notes]
 +
* [https://stribika.github.io/2015/01/04/secure-secure-shell.html Secure Secure Shell]

Latest revision as of 05:29, 24 November 2016

SSH keys serve as a means of identifying yourself to an SSH server using public-key cryptography and challenge-response authentication. One immediate advantage 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 convenient 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.

Background

SSH keys are always generated in pairs with one known as the private key and the other as the public key. 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 wish to connect.

If 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 an encrypted message and it must be met with the appropriate response before the server will grant you access. What makes this coded message particularly secure is that it can only be understood by the private key holder. 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 to correctly understand the challenge and produce the proper response.

This challenge-response phase happens behind the scenes and is invisible to the user. As long as 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.

A private key is a guarded secret and as such it is advisable to store it on disk in an encrypted form. When the encrypted private key is required, a passphrase must first be entered in order to decrypt it. While this might superficially appear as though you are providing a login password to the SSH server, the passphrase is only used to decrypt the private key on the local system. The passphrase is not transmitted over the network.

Generating an SSH key pair

An SSH key pair can be generated by running the ssh-keygen command, defaulting to 2048-bit RSA (and SHA256) which the ssh-keygen(1) man page says is "generally considered sufficient" and should be compatible with virtually all clients and servers:

$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/<username>/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/<username>/.ssh/id_rsa.
Your public key has been saved in /home/<username>/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:gGJtSsV8BM+7w018d39Ji57F8iO6c0N2GZq3/RY2NhI username@hostname
The key's randomart image is:
+---[RSA 2048]----+
|   ooo.          |
|   oo+.          |
|  + +.+          |
| o +   +     E . |
|  .   . S . . =.o|
|     . + . . B+@o|
|      + .   oo*=O|
|       .   ..+=o+|
|           o=ooo+|
+----[SHA256]-----+

The randomart image was introduced in OpenSSH 5.1 as an easier means of visually identifying the key fingerprint.

You can also add an optional comment field to the public key with the -C switch, to more easily identify it in places such as ~/.ssh/known_hosts, ~/.ssh/authorized_keys and ssh-add -L output. For example:

$ ssh-keygen -C "$(whoami)@$(hostname)-$(date -I)"

will add a comment saying which user created the key on which machine and when.

The -o switch can also be used to save the private key in the new OpenSSH format, which has increased resistance to brute-force password cracking (but is not supported by versions of OpenSSH prior to 6.5 released 2014-01-29). Use the -a switch to specify the number of KDF rounds. According to ssh-keygen(1), Ed25519 keys always use the new private key format.

Choosing the type of encryption

OpenSSH supports several key exchange algorithms which can be divided in two groups depending on the mathematical properties they exploit:

  1. DSA and RSA, which rely on the practical difficulty of factoring the product of two large prime numbers,
  2. ECDSA and Ed25519, which rely on the elliptic curve discrete logarithm problem. (example)

Elliptic curve cryptography (ECC) algorithms are a more recent addition to public key cryptosystems. One of their main advantages is their ability to provide the same level of security with smaller keys, which makes for less computationally intensive operations (i.e. faster key creation, encryption and decryption) and reduced storage and transmission requirements.

OpenSSH 7.0 deprecated and disabled support for DSA keys due to discovered vulnerabilities, therefore the choice of cryptosystem lies within RSA or one of the two types of ECC.

#RSA keys will give you the greatest portability, while #Ed25519 will give you the best security but requires recent versions of client & server[1]. #ECDSA is likely more compatible than Ed25519 (though still less than RSA), but suspicions exist about its security (see below).

Note:
  • As of July 10, 2015, GNOME Keyring does not handle ECDSA[2] and Ed25519[3] keys. Users will have to turn to other SSH agents or stick to RSA keys.
  • These keys are used only to authenticate you; choosing stronger keys will not increase CPU load when transferring data over SSH.

RSA

ssh-keygen defaults to RSA therefore there is no need to specify it with the -t option. It provides the best compatibility of all algorithms but requires the key size to be larger to provide sufficient security.

Minimum key size is 1024 bits, default is 2048 (see ssh-keygen(1)) and maximum is 16384:

$ ssh-keygen -b 32768
key bits exceeds maximum 16384

If you wish to generate a stronger RSA key pair (e.g. to guard against cutting-edge or unknown attacks and more sophisticated attackers), simply specify the -b option with a higher bit value than the default:

$ ssh-keygen -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/home/<username>/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/<username>/.ssh/id_rsa.
Your public key has been saved in /home/<username>/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:+Pqo84NC+vAQQ9lUV0z+/zPHsyCe8oZpy6hLkIa7qfk <username>@<hostname>
The key's randomart image is:
+---[RSA 4096]----+
|   ... .+o       |
|  +   . ..       |
| o .     .       |
|. . .  .  .      |
|o. +  . S  .     |
| o+ .  .    .    |
|o+   o  . o. o . |
|.=+ + .oo=..o o+o|
|+=E..**+oo=+   o*|
+----[SHA256]-----+

Be aware though that there are diminishing returns in using longer keys.[4][5] The GnuPG FAQ reads: "If you need more security than RSA-2048 offers, the way to go would be to switch to elliptical curve cryptography — not to continue using RSA".[6]

On the other hand, the latest iteration of the NSA Fact Sheet Suite B Cryptography suggests a minimum 3072-bit modulus for RSA while "[preparing] for the upcoming quantum resistant algorithm transition".[7]

ECDSA

Note: The Windows SSH client PuTTY does not support ECDSA as of March 2016. One needs a PuTTY development snapshot to connect to a server that uses only ECDSA keys.[8]

The Elliptic Curve Digital Signature Algorithm (ECDSA) was introduced as the preferred algorithm for authentication in OpenSSH 5.7. Some vendors also disable the required implementations due to potential patent issues.

There are two sorts of concerns with it:

  1. Political concerns, the trustworthiness of NIST-produced curves being questioned after revelations that the NSA willingly inserts backdoors into softwares, hardware components and published standards were made; well-known cryptographers have expressed doubts about how the NIST curves were designed, and voluntary tainting has already been proved in the past.
  2. Technical concerns, about the difficulty to properly implement the standard and the slowness and design flaws which reduce security in insufficiently precautious implementations.

Both of those concerns are best summarized in libssh curve25519 introduction. Although the political concerns are still subject to debate, there is a clear consensus that #Ed25519 is technically superior and should therefore be preferred.

Ed25519

Ed25519 was introduced in OpenSSH 6.5: "Ed25519 is an elliptic curve signature scheme that offers better security than ECDSA and DSA and good performance". Its main strengths are its speed, its constant-time run time (and resistance against side-channel attacks), and its lack of nebulous hard-coded constants.[9] See also this blog post by a Mozilla developer on how it works.

It is already implemented in many applications and libraries and is the default key exchange algorithm (which is different from key signature) in OpenSSH.

Ed25519 key pairs can be generated with:

$ ssh-keygen -t ed25519

There is no need to set the key size, as all Ed25519 keys are 256 bits. Also, they rely on a new key format which "uses a bcrypt-based key derivation function that makes brute-force attacks against stolen private keys far slower".

For those reasons, compatibility with older versions of OpenSSH or other SSH clients and servers may prove troublesome.

Choosing the key location and passphrase

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

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 key 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.

Changing the private key's passphrase without changing the key

If the originally chosen SSH key passphrase is undesirable or must be changed, one can use the ssh-keygen command to change the passphrase without changing the actual key.

To change the passphrase for the private RSA key, run the following command:

$ ssh-keygen -f ~/.ssh/id_rsa -p

Managing multiple keys

It is possible —although not considered best practice— to use the same SSH key pair for multiple hosts.

On the other hand, it is rather easy to maintain distinct keys for multiple hosts by using the IdentityFile directive in your openSSH config file:

~/.ssh/config
Host SERVER1
   IdentitiesOnly yes
   IdentityFile ~/.ssh/id_rsa_SERVER1

Host SERVER2
   IdentitiesOnly yes
   IdentityFile ~/.ssh/id_ed25519_SERVER2

See ssh_config(5) for full description of these options.

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 it is appended with a .pub extension. Note that the private key is not shared and remains on the local machine.

Simple method

Note: This method might fail if the remote server uses a non-sh shell such as tcsh as default and uses OpenSSH older than 6.6.1p1. See this bug report.

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

$ ssh-copy-id remote-server.org

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

$ ssh-copy-id username@remote-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_ed25519.pub username@remote-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_ed25519.pub -p 221 username@remote-server.org

Manual 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 username@remote-server.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 username@remote-server.org
username@remote-server.org's password:
$ mkdir ~/.ssh
$ chmod 700 ~/.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.

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 to run automatically upon login and persist for the duration of your login session. A variety of agents, front-ends, and configurations exist to achieve this effect. This section provides an overview of a number of different solutions which can be adapted to meet your specific needs.

ssh-agent

ssh-agent is the default agent included with OpenSSH. It can be used directly or serve as the back-end to a few of the front-end solutions mentioned later in this section. When ssh-agent is run, it forks to background and prints necessary environment variables. E.g.

$ 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;

To make use of these variables, run the command through the eval command.

$ eval $(ssh-agent)
Agent pid 2157

Once ssh-agent is running, you will need to add your private key to its cache:

$ 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)

If your private key is encrypted, ssh-add will prompt you to enter your passphrase. Once your private key has been successfully added to the agent you will be able to make SSH connections without having to enter your passphrase.

Tip: To make all ssh clients, including git store keys in the agent on first use, add the configuration setting AddKeysToAgent yes to ~/.ssh/config. Other possible values are confirm, ask and no (default).

In order to start the agent automatically and make sure that only one ssh-agent process runs at a time, add the following to your ~/.bashrc:

if ! pgrep -u $USER ssh-agent > /dev/null; then
    ssh-agent > ~/.ssh-agent-thing
fi
if [[ "$SSH_AGENT_PID" == "" ]]; then
    eval $(<~/.ssh-agent-thing)
fi

This will run a ssh-agent process if there is not one already, and save the output thereof. If there is one running already, we retrieve the cached ssh-agent output and evaluate it which will set the necessary environment variables.

There also exist a number of front-ends to ssh-agent and alternative agents described later in this section which avoid this problem.

Start ssh-agent with systemd user

It is possible to use the systemd/User facilities to start the agent.

~/.config/systemd/user/ssh-agent.service
[Unit]
Description=SSH key agent

[Service]
Type=forking
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket
ExecStart=/usr/bin/ssh-agent -a $SSH_AUTH_SOCK

[Install]
WantedBy=default.target

Add export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/ssh-agent.socket" to your shell's startup file, for example .bash_profile for Bash. Then enable or start the service.

ssh-agent as a wrapper program

An alternative way to start ssh-agent (with, say, each X session) is described in this ssh-agent tutorial by UC Berkeley Labs. A basic use case is if you normally begin X with the startx command, you can instead prefix it with ssh-agent like so:

$ ssh-agent startx

And so you do not even need to think about it you can put an alias in your .bash_aliases file or equivalent:

alias startx='ssh-agent startx'

Doing it this way avoids the problem of having extraneous ssh-agent instances floating around between login sessions. Exactly one instance will live and die with the entire X session.

Note: You can also add eval $(ssh-agent) to ~/.xinitrc.

See the below notes on using x11-ssh-askpass with ssh-add for an idea on how to immediately add your key to the agent.

GnuPG Agent

The gpg-agent has OpenSSH agent emulation. See GnuPG#SSH agent for necessary configuration.

Keychain

Keychain is a program designed to help you easily manage your SSH keys with minimal user interaction. It is implemented as a shell script which drives both ssh-agent and ssh-add. A notable feature of Keychain is that it can maintain a single ssh-agent process across multiple login sessions. This means that you only need to enter your passphrase once each time your local machine is booted.

Installation

Install the keychain package available from the official repositories.

Configuration

Warning: As of 2015-09-26, the -Q, --quick option has the unexpected side-effect of making keychain switch to a newly-spawned ssh-agent upon relogin (at least on systems using GNOME), forcing you to re-add all the previously registered keys.

Add a line similar to the following to your shell configuration file, e.g. if using Bash:

~/.bashrc
eval $(keychain --eval --quiet id_ed25519 id_rsa ~/.keys/my_custom_key)
Note: ~/.bashrc is used instead of the upstream suggested ~/.bash_profile because on Arch it is sourced by both login and non-login shells, making it suitable for textual and graphical environments alike. See Bash#Invocation for more information on the difference between those.

In the above example,

  • the --eval switch outputs lines to be evaluated by the opening eval command; this sets the necessary environments variables for SSH client to be able to find your agent.
  • --quiet will limit output to warnings, errors, and user prompts.

Multiple keys can be specified on the command line, as shown in the example. By default keychain will look for key pairs in the ~/.ssh/ directory, but absolute path can be used for keys in non-standard location. You may also use the --confhost option to inform keychain to look in ~/.ssh/config for IdentityFile settings defined for particular hosts, and use these paths to locate keys.

See keychain --help or man keychain for details on setting keychain for other shells.

To test Keychain, simply open a new terminal emulator or log out and back in your session. It should prompt you for the passphrase of the specified private key(s) (if applicable), either using the program set in $SSH_ASKPASS or on the terminal.

Because Keychain reuses the same ssh-agent process on successive logins, you should not have to enter your passphrase the next time you log in or open a new terminal. You will only be prompted for your passphrase once each time the machine is rebooted.

Tips

  • keychain expects public key files to exist in the same directory as their private counterparts, with a .pub extension. If the private key is a symlink, the public key can be found alongside the symlink or in the same directory as the symlink target (this capability requires the readlink command to be available on the system).
  • to disable the graphical prompt and always enter your passphrase on the terminal, use the --nogui option. This allows to copy-paste long passphrases from a password manager for example.
  • if you do not want to be immediately prompted for unlocking the keys but rather wait until they are needed, use the --noask option.
Note: Keychain is able to manage GPG keys in the same fashion. By default it attempts to start ssh-agent only, but you can modify this behavior using the --agents option, e.g. --agents ssh,gpg. See man keychain.

envoy

An alternative to keychain is envoy. Envoy is available as envoy , or the Git version as envoy-gitAUR.

After installing it, set up the envoy socket by enabling envoy@ssh-agent.socket.

And add to your shell's rc file:

envoy -t ssh-agent -a ssh_key
source <(envoy -p)

If this syntax for sourcing causes errors (in mksh, for example), you can replace it with:

envoy -t ssh-agent -a ssh_key
eval "$(envoy -p)"

If the key is ~/.ssh/id_rsa, ~/.ssh/id_dsa, ~/.ssh/id_ecdsa, or ~/.ssh/identity, the -a ssh_key parameter is not needed.

envoy with key passphrases stored in kwallet

If you have long passphrases for your SSH keys, remembering them can be a pain. So let us tell kwallet to store them! Along with envoy, install ksshaskpass and kwalletmanager from the official repositories. Next, enable the envoy socket in systemd (see above).

Note: As of April 30, 2015, if after installation ksshaskpass keeps asking for access to your wallet even after having submitted the password, you might have this problem. The proposed solution is to install ksshaskpass4AUR, though this might break your login.

First, you will add this script to ~/.kde4/Autostart/ssh-agent.sh:

#!/bin/sh
envoy -t ssh-agent -a ssh_key

Then, make sure the script is executable by running: chmod +x ~/.kde4/Autostart/ssh-agent.sh

And add this to ~/.kde4/env/ssh-agent.sh:

#!/bin/sh
eval $(envoy -p)

When you log into KDE, it will execute the ssh-agent.sh script. This will call ksshaskpass, which will prompt you for your kwallet password when envoy calls ssh-agent.

x11-ssh-askpass

The x11-ssh-askpass package provides a graphical dialog for entering your passhrase when running an X session. x11-ssh-askpass depends only on the libx11 and libxt libraries, and the appearance of x11-ssh-askpass is customizable. While it can be invoked by the ssh-add program, which will then load your decrypted keys into ssh-agent, the following instructions will, instead, configure x11-ssh-askpass to be invoked by the aforementioned Keychain script.

Install keychain and x11-ssh-askpass, both available in the official repositories.

Edit your ~/.xinitrc file to include the following lines, replacing the name and location of your private key if necessary. Be sure to place these commands before the line which invokes your window manager.

~/.xinitrc
keychain ~/.ssh/id_ecdsa
[ -f ~/.keychain/$HOSTNAME-sh ] && . ~/.keychain/$HOSTNAME-sh 2>/dev/null
[ -f ~/.keychain/$HOSTNAME-sh-gpg ] && . ~/.keychain/$HOSTNAME-sh-gpg 2>/dev/null
...
exec openbox-session

In the above example, the first line invokes keychain and passes the name and location of your private key. If this is not the first time keychain was invoked, the following two lines load the contents of $HOSTNAME-sh and $HOSTNAME-sh-gpg, if they exist. These files store the environment variables of the previous instance of keychain.

Calling x11-ssh-askpass with ssh-add

The ssh-add manual page specifies that, in addition to needing the DISPLAY variable defined, you also need SSH_ASKPASS set to the name of your askpass program (in this case x11-ssh-askpass). It bears keeping in mind that the default Arch Linux installation places the x11-ssh-askpass binary in /usr/lib/ssh/, which will not be in most people's PATH. This is a little annoying, not only when declaring the SSH_ASKPASS variable, but also when theming. You have to specify the full path everywhere. Both inconveniences can be solved simultaneously by symlinking:

$ ln -sv /usr/lib/ssh/x11-ssh-askpass ~/bin/ssh-askpass

This is assuming that ~/bin is in your PATH. So now in your .xinitrc, before calling your window manager, one just needs to export the SSH_ASKPASS environment variable:

$ export SSH_ASKPASS=ssh-askpass

and your X resources will contain something like:

ssh-askpass*background: #000000

Doing it this way works well with the above method on using ssh-agent as a wrapper program. You start X with ssh-agent startx and then add ssh-add to your window manager's list of start-up programs.

Theming

The appearance of the x11-ssh-askpass dialog can be customized by setting its associated X resources. The x11-ssh-askpass home page[dead link 2015-04-01] presents some example themes[dead link 2015-04-01]. See the x11-ssh-askpass manual page for full details.

Alternative passphrase dialogs

There are other passphrase dialog programs which can be used instead of x11-ssh-askpass. The following list provides some alternative solutions.

  • ksshaskpass is available in the official repositories. It is dependent on kdelibs and is suitable for the KDE Desktop Environment.
  • openssh-askpass depends on the qt4 libraries and is available from the official repositories.

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.

Note: pam_ssh 2.0 now requires that all private keys used in the authentication process be located under ~/.ssh/login-keys.d/.

Create a symlink to your private key file and place it in ~/.ssh/login-keys.d/. Replace the id_rsa in the example below with the name of your own private key file.

$ mkdir ~/.ssh/login-keys.d/
$ cd ~/.ssh/login-keys.d/
$ ln -s ../id_rsa

Edit the /etc/pam.d/login configuration file to include the text 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.
/etc/pam.d/login
#%PAM-1.0

auth       required     pam_securetty.so
auth       requisite    pam_nologin.so
auth       include      system-local-login
auth       optional     pam_ssh.so        try_first_pass
account    include      system-local-login
session    include      system-local-login
session    optional     pam_ssh.so

In the above example, login authentication initially proceeds as it normally would, with the user being prompted to enter his user password. The additional auth authentication rule added to the end of the authentication stack then instructs the pam_ssh module to try to decrypt any private keys found in the ~/.ssh/login-keys.d directory. The try_first_pass option is passed to the pam_ssh module, instructing it to first try to decrypt any SSH private keys using the previously entered user password. If the user's private key passphrase and user password are the same, this should succeed and the user will not be prompted to enter the same password twice. In the case where the user's private key passphrase user password differ, the pam_ssh module will prompt the user to enter the SSH passphrase after the user password has been entered. The optional control value ensures that users without an SSH private key are still able to log in. In this way, the use of pam_ssh will be transparent to users without an SSH private key.

If you use 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.

Using a different password to unlock the SSH key

If you want to unlock the SSH keys or not depending on whether you use your key's passphrase or the (different!) login password, you can modify /etc/pam.d/system-auth to

/etc/pam.d/system-auth
#%PAM-1.0

auth      [success=1 new_authtok_reqd=1 ignore=ignore default=ignore]  pam_unix.so     try_first_pass nullok
auth      required  pam_ssh.so      use_first_pass
auth      optional  pam_permit.so
auth      required  pam_env.so

account   required  pam_unix.so
account   optional  pam_permit.so
account   required  pam_time.so

password  required  pam_unix.so     try_first_pass nullok sha512 shadow
password  optional  pam_permit.so

session   required  pam_limits.so
session   required  pam_unix.so
session   optional  pam_permit.so
session   optional  pam_ssh.so

For an explanation, see here.

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.

  • Versions of pam_ssh prior to version 2.0 do not support SSH keys employing the newer option of ECDSA (elliptic curve) cryptography. If you are using earlier versions of 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 because 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 Keychain front-end 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. See the GNOME Keyring article for further details.

Store SSH keys with Kwallet

For instructions on how to use kwallet to store your SSH keys, see KDE Wallet#Using the KDE Wallet to store ssh keys.

KeePass2 with KeeAgent plugin

KeeAgent is a plugin for KeePass that allows SSH keys stored in a KeePass database to be used for SSH authentication by other programs.

  • Supports both PuTTY and OpenSSH private key formats.
  • Works with native SSH agent on Linux/Mac and with PuTTY on Windows.

See KeePass#Plugin Installation or install the keepass-plugin-keeagentAUR package. There is also the beta version, where new features appear first, keepass-plugin-keeagent-betaAUR.

Troubleshooting

Key ignored by the server

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

If that does not solve the problem you may try temporarily setting StrictModes to no in sshd_config. If authentication with StrictModes off is successful, it is likely an issue with file permissions persists.

Tip: Do not forget to set StrictModes to yes for added security.

Make sure the remote machine supports the type of keys you are using. Try using RSA or DSA keys instead #Generating an SSH key pair

Some servers do not support ECDSA keys. 

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

# /usr/bin/sshd -d

See also