https://wiki.archlinux.org/api.php?action=feedcontributions&user=Fethbita&feedformat=atomArchWiki - User contributions [en]2024-03-28T12:33:31ZUser contributionsMediaWiki 1.41.0https://wiki.archlinux.org/index.php?title=SSH_keys&diff=731846SSH keys2022-06-06T14:06:15Z<p>Fethbita: Undo revision 731845 by Fethbita (talk) ~/.pam_environment is deprecated</p>
<hr />
<div>[[Category:Secure Shell]]<br />
[[es:SSH keys]]<br />
[[ja:SSH 鍵]]<br />
[[zh-hans:SSH keys]]<br />
{{Expansion|The intro and ''Background'' section ignore the server perspective.}}<br />
<br />
SSH keys can 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]]. The major advantage of key-based authentication is that, in contrast to password authentication, it is not prone to [[Wikipedia:Brute-force attack|brute-force attacks]], and you do not expose valid credentials if the server has been compromised (see [[RFC:4251#section-9.4.4|RFC 4251 9.4.4]]).<br />
<br />
Furthermore, 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.<br />
<br />
Key-based authentication is not without its drawbacks and may not be appropriate for all environments, but in many circumstances it 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. <br />
<br />
This article assumes you already have a basic understanding of the [[Secure Shell]] protocol and have [[install]]ed the {{Pkg|openssh}} package.<br />
<br />
== Background ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
This [[Wikipedia:Challenge-response authentication|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.<br />
<br />
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.<br />
<br />
== Generating an SSH key pair ==<br />
<br />
An SSH key pair can be generated by running the {{ic|ssh-keygen}} command, defaulting to 3072-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:<br />
<br />
{{hc<br />
|$ ssh-keygen<br />
|<nowiki>Generating public/private rsa key pair.<br />
Enter file in which to save the key (/home/<username>/.ssh/id_rsa): <br />
Enter passphrase (empty for no passphrase): <br />
Enter same passphrase again: <br />
Your identification has been saved in /home/<username>/.ssh/id_rsa.<br />
Your public key has been saved in /home/<username>/.ssh/id_rsa.pub.<br />
The key fingerprint is:<br />
SHA256:gGJtSsV8BM+7w018d39Ji57F8iO6c0N2GZq3/RY2NhI username@hostname<br />
The key's randomart image is:<br />
+---[RSA 3072]----+<br />
| ooo. |<br />
| oo+. |<br />
| + +.+ |<br />
| o + + E . |<br />
| . . S . . =.o|<br />
| . + . . B+@o|<br />
| + . oo*=O|<br />
| . ..+=o+|<br />
| o=ooo+|<br />
+----[SHA256]-----+</nowiki>}}<br />
<br />
The [https://www.cs.berkeley.edu/~dawnsong/papers/randomart.pdf randomart image] was [https://www.openssh.com/txt/release-5.1 introduced in OpenSSH 5.1] as an easier means of visually identifying the key fingerprint.<br />
<br />
{{Note|You can use the {{ic|-a}} switch to specify the number of KDF rounds on the password encryption.}}<br />
<br />
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:<br />
<br />
$ ssh-keygen -C "$(whoami)@$(uname -n)-$(date -I)"<br />
<br />
will add a comment saying which user created the key on which machine and when.<br />
<br />
=== Choosing the authentication key type ===<br />
<br />
OpenSSH supports several signing algorithms (for authentication keys) which can be divided in two groups depending on the mathematical properties they exploit:<br />
<br />
# [[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,<br />
# [[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/content/certicom/en/52-the-elliptic-curve-discrete-logarithm-problem.html example])<br />
<br />
[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.<br />
<br />
OpenSSH 7.0 [https://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.<br />
<br />
[[#RSA]] keys will give you the greatest portability, while [[#Ed25519]] will give you the best security but requires recent versions of client & server[https://web.archive.org/web/20191222003107/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).<br />
<br />
{{Note|These keys are used only to authenticate you; choosing stronger keys will not increase CPU load when transferring data over SSH.<br />
}}<br />
<br />
==== RSA ====<br />
<br />
{{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.<br />
<br />
Minimum key size is 1024 bits, default is 3072 (see {{man|1|ssh-keygen}}) and maximum is 16384.<br />
<br />
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:<br />
<br />
$ ssh-keygen -b 4096<br />
<br />
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]<br />
<br />
On the other hand, the latest iteration of the [https://web.archive.org/web/20160305203915/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''".[https://www.keylength.com/en/6/]<br />
<br />
==== ECDSA ====<br />
<br />
The Elliptic Curve Digital Signature Algorithm (ECDSA) was introduced as the preferred algorithm for authentication [https://www.openssh.com/txt/release-5.7 in OpenSSH 5.7]. Some vendors also disable the required implementations due to potential patent issues.<br />
<br />
There are two sorts of concerns with it:<br />
<br />
# ''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] [https://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] [https://www.scientificamerican.com/article/nsa-nist-encryption-scandal/ proven] in the past.<br />
# ''Technical concerns'', about the [https://blog.cr.yp.to/20140323-ecdsa.html difficulty to properly implement the standard] and the [https://www.gossamer-threads.com/lists/openssh/dev/57162#57162 slowness and design flaws] which reduce security in insufficiently precautious implementations. <br />
<br />
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.<br />
<br />
==== Ed25519 ====<br />
<br />
[https://ed25519.cr.yp.to/ Ed25519] was introduced in [https://www.openssh.com/txt/release-6.5 OpenSSH 6.5] of January 2014: "''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.<br />
<br />
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.<br />
<br />
Ed25519 key pairs can be generated with:<br />
<br />
$ ssh-keygen -t ed25519<br />
<br />
There is no need to set the key size, as all Ed25519 keys are 256 bits.<br />
<br />
Keep in mind that older SSH clients and servers may not support these keys.<br />
<br />
==== FIDO/U2F ====<br />
<br />
FIDO/[[U2F]] [[Wikipedia:Security token|hardware authenticator]] support was added in [https://www.openssh.com/txt/release-8.2 OpenSSH version 8.2] for both of the elliptic curve signature schemes mentioned above. It allows for a hardware token attached via USB or other means to act a second factor alongside the private key. <br />
<br />
{{Note|Both the client and server must support the {{ic|ed25519-sk}} and {{ic|ecdsa-sk}} key types.}}<br />
<br />
The {{Pkg|libfido2}} is required for hardware token support.<br />
<br />
{{Note|OpenSSH uses a middleware library to communicate with the hardware token and comes with an internal middleware which supports USB tokens. Other middleware may be specified by the {{man|5|sshd_config|SecurityKeyProvider}} directive or the {{ic|SSH_SK_PROVIDER}} environment variable for {{ic|ssh-keygen}} and {{ic|ssh-add}}.}}<br />
<br />
After attaching a compatible FIDO key, a key pair may be generated with:<br />
<br />
$ ssh-keygen -t ed25519-sk<br />
<br />
You will usually be required to enter your PIN and/or tap your token to confirm the generation. Connecting to a server will usually require tapping your token unless the {{ic|-O no-touch-required}} command line option is used during generation and the {{man|8|sshd|no-touch-required}} {{ic|authorized_keys}} option is set on the server.<br />
<br />
To create keys that do not require touch events, generate a key pair with the {{ic|no-touch-required}} option. For example:<br />
<br />
$ ssh-keygen -O no-touch-required -t ed25519-sk<br />
<br />
{{Note|Not all hardware tokens support this option. If you are using a YubiKey, firmware version 5.2.3 is needed for the ed25519-sk key type.[https://www.yubico.com/blog/whats-new-in-yubikey-firmware-5-2-3/]}}<br />
<br />
Additionally, {{ic|sshd}} rejects {{ic|no-touch-required}} keys by default. To allow keys generated with this option, either enable it for an individual key in the {{ic|authorized_keys}} file,<br />
<br />
no-touch-required sk-ssh-ed25519@openssh.com AAAAInN... user@example.com<br />
<br />
or for the whole system by editing {{ic|/etc/ssh/sshd_config}} with<br />
<br />
PubkeyAuthOptions none<br />
<br />
An ECDSA-based keypair may also be generated with the {{ic|ecdsa-sk}} keytype, but the relevant concerns in the [[#ECDSA]] section above still apply.<br />
<br />
$ ssh-keygen -t ecdsa-sk<br />
<br />
=== Choosing the key location and passphrase ===<br />
<br />
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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
{{Note|Previously, the private key password was encoded in an insecure way: only a single round of an MD5 hash. OpenSSH 6.5 and later support a new, more secure format to encode your private key. This format is the default since [https://www.openssh.com/txt/release-7.8 OpenSSH version 7.8]. Ed25519 keys have always used the new encoding format. To upgrade to the new format, simply change the key's passphrase, as described in the next section.}}<br />
<br />
==== Changing the private key's passphrase without changing the key ====<br />
<br />
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. This can also be used to change the password encoding format to the new standard.<br />
<br />
$ ssh-keygen -f ~/.ssh/id_rsa -p<br />
<br />
==== Managing multiple keys ====<br />
<br />
If you have multiple SSH identities, you can set different keys to be used for different hosts or remote users by using the {{ic|Match}} and {{ic|IdentityFile}} directives in your configuration:<br />
<br />
{{hc|~/.ssh/config|2=<br />
Match host=SERVER1<br />
IdentitiesOnly yes<br />
IdentityFile ~/.ssh/id_rsa_IDENTITY1<br />
<br />
Match host=SERVER2,SERVER3<br />
IdentitiesOnly yes<br />
IdentityFile ~/.ssh/id_ed25519_IDENTITY2<br />
}}<br />
<br />
See {{man|5|ssh_config}} for full description of these options.<br />
<br />
==== Storing SSH keys on hardware tokens ====<br />
<br />
{{Expansion|[https://www.openssh.com/txt/release-8.2 OpenSSH version 8.2] adds support for FIDO2 resident keys, allowing SSH Keys to be stored on the hardware token.}}<br />
<br />
SSH keys can also be stored on a security token like a smart card or a USB token. This has the advantage that the private key is stored securely on the token instead of being stored on disk. When using a security token the sensitive private key is also never present in the RAM of the PC; the cryptographic operations are performed on the token itself. A cryptographic token has the additional advantage that it is not bound to a single computer; it can easily be removed from the computer and carried around to be used on other computers.<br />
<br />
Examples are hardware tokens are described in:<br />
<br />
* [[YubiKey#SSH notes]] Native OpenSSH support for FIDO/U2F keys<br />
* [[YubiKey#SSH keys]]<br />
* [[Trusted Platform Module#Securing SSH keys]]<br />
<br />
== Copying the public key to the remote server ==<br />
<br />
{{Expansion|How to do this if you [[OpenSSH#Force public key authentication|force public key authentication]]?}}<br />
<br />
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.<br />
<br />
=== Simple method ===<br />
<br />
{{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].}}<br />
<br />
If your key file is {{ic|~/.ssh/id_rsa.pub}} you can simply enter the following command.<br />
<br />
$ ssh-copy-id remote-server.org<br />
<br />
If your username differs on remote machine, be sure to prepend the username followed by {{ic|@}} to the server name.<br />
<br />
$ ssh-copy-id username@remote-server.org<br />
<br />
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.<br />
<br />
$ ssh-copy-id -i ~/.ssh/id_ed25519.pub username@remote-server.org<br />
<br />
If the ssh server is listening on a port other than default of 22, be sure to include it within the host argument.<br />
<br />
$ ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 221 username@remote-server.org<br />
<br />
=== Manual method ===<br />
<br />
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.<br />
<br />
$ scp ~/.ssh/id_ecdsa.pub username@remote-server.org:<br />
<br />
The above example copies the public key ({{ic|id_ecdsa.pub}}) to your home directory on the remote server via {{ic|scp}}. Do not forget to include the {{ic|:}} at the end of the server address. Also note that the name of your public key may differ from the example given.<br />
<br />
On the remote server, you will need to create the {{ic|~/.ssh}} directory if it does not yet exist and append your public key to the {{ic|authorized_keys}} file.<br />
<br />
$ ssh username@remote-server.org<br />
username@remote-server.org's password:<br />
$ mkdir ~/.ssh<br />
$ chmod 700 ~/.ssh<br />
$ cat ~/id_ecdsa.pub >> ~/.ssh/authorized_keys<br />
$ rm ~/id_ecdsa.pub<br />
$ chmod 600 ~/.ssh/authorized_keys<br />
<br />
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.<br />
<br />
== SSH agents ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
=== ssh-agent ===<br />
<br />
{{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.<br />
<br />
{{hc|$ ssh-agent|2=<br />
SSH_AUTH_SOCK=/tmp/ssh-vEGjCM2147/agent.2147; export SSH_AUTH_SOCK;<br />
SSH_AGENT_PID=2148; export SSH_AGENT_PID;<br />
echo Agent pid 2148;<br />
}}<br />
<br />
To make use of these variables, run the command through the {{ic|eval}} command.<br />
<br />
{{hc|$ eval $(ssh-agent)|<br />
Agent pid 2157<br />
}}<br />
<br />
Once {{ic|ssh-agent}} is running, you will need to add your private key to its cache:<br />
<br />
{{hc|$ ssh-add ~/.ssh/id_ed25519|<br />
Enter passphrase for /home/user/.ssh/id_ed25519:<br />
Identity added: /home/user/.ssh/id_ed25519 (/home/user/.ssh/id_ed25519)<br />
}}<br />
<br />
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 your passphrase.<br />
<br />
{{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).}}<br />
<br />
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}}:<br />
<br />
{{bc|<nowiki><br />
if ! pgrep -u "$USER" ssh-agent > /dev/null; then<br />
ssh-agent -t 1h > "$XDG_RUNTIME_DIR/ssh-agent.env"<br />
fi<br />
if [[ ! "$SSH_AUTH_SOCK" ]]; then<br />
source "$XDG_RUNTIME_DIR/ssh-agent.env" >/dev/null<br />
fi<br />
</nowiki>}}<br />
<br />
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. The lifetime of the unlocked keys is set to 1 hour.<br />
<br />
There also exist a number of front-ends to {{ic|ssh-agent}} and alternative agents described later in this section which avoid this problem.<br />
<br />
==== Start ssh-agent with systemd user ====<br />
<br />
It is possible to use the [[systemd/User]] facilities to start the agent. Use this if you would like your ssh agent to run when you are logged in, regardless of whether x is running.<br />
<br />
{{hc|~/.config/systemd/user/ssh-agent.service|2=<br />
[Unit]<br />
Description=SSH key agent<br />
<br />
[Service]<br />
Type=simple<br />
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket<br />
# DISPLAY required for ssh-askpass to work<br />
Environment=DISPLAY=:0<br />
ExecStart=/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then ''export'' the [[environment variable]] {{ic|1=SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/ssh-agent.socket"}} in your [[login shell]] initialization file, such as {{ic|~/.bash_profile}} or {{ic|~/.zprofile}}.<br />
<br />
Finally, [[enable]] or [[start]] the service with the {{ic|--user}} flag.<br />
<br />
{{Note|<br />
* If you use GNOME, this environment variable is overridden by default. See [[GNOME/Keyring#Disable keyring daemon components]].<br />
* Make sure to not overwrite an existing {{ic|SSH_AUTH_SOCK}} if you want to be able to use a [[OpenSSH#Agent forwarding|forwarded ssh agent]].<br />
}}<br />
<br />
{{Tip|When starting the agent via systemd as described above, it is possible to automatically enter the passphrase of your default key and add it to the agent. See [https://github.com/capocasa/systemd-user-pam-ssh systemd-user-pam-ssh] for details.}}<br />
<br />
==== ssh-agent as a wrapper program ====<br />
<br />
An alternative way to start ssh-agent (with, say, each X session) is described in [https://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:<br />
<br />
$ ssh-agent startx<br />
<br />
And so you do not even need to think about it you can put an alias in your {{ic|.bash_aliases}} file or equivalent:<br />
<br />
alias startx='ssh-agent startx'<br />
<br />
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.<br />
<br />
{{Note|{{ic|ssh-askpass}} requires the {{ic|DISPLAY}} environment variable to work, so you may want to run {{ic|ssh-agent}} in {{ic|~/.xinitrc}} instead of {{ic|ssh-agent startx}}, where {{ic|DISPLAY}} is set. For example, you can add {{ic|exec ssh-agent dbus-launch i3}} to {{ic|~/.xinitrc}}. Or as an alternative to using {{ic|ssh-agent}} as a wrapper program, you can add {{ic|eval $(ssh-agent)}} to {{ic|~/.xinitrc}}.}}<br />
<br />
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.<br />
<br />
=== GnuPG Agent ===<br />
<br />
The [[gpg-agent]] has OpenSSH Agent protocol emulation. See [[GnuPG#SSH agent]] for necessary configuration.<br />
<br />
=== Keychain ===<br />
<br />
[[Funtoo: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.<br />
<br />
==== Installation ====<br />
<br />
[[Install]] the {{Pkg|keychain}} package.<br />
<br />
==== Configuration ====<br />
<br />
{{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.}}<br />
<br />
Add a line similar to the following to your [[shell]] configuration file, ''e.g.'' if using [[Bash]]:<br />
<br />
{{hc|~/.bashrc|<br />
eval $(keychain --eval --quiet id_ed25519 id_rsa ~/.keys/my_custom_key)<br />
}}<br />
<br />
{{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.}}<br />
<br />
In the above example,<br />
* the {{ic|--eval}} switch outputs lines to be evaluated by the opening {{ic|eval}} command; this sets the necessary environment variables for an SSH client to be able to find your agent.<br />
* {{ic|--quiet}} will limit output to warnings, errors, and user prompts.<br />
<br />
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.<br />
<br />
See {{ic|keychain --help}} or {{man|1|keychain}} for details on setting ''keychain'' for other shells.<br />
<br />
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.<br />
<br />
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.<br />
<br />
==== Tips ====<br />
<br />
* ''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).<br />
<br />
*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.<br />
<br />
*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.<br />
<br />
{{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 {{man|1|keychain}}.}}<br />
<br />
=== x11-ssh-askpass ===<br />
<br />
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.<br />
<br />
Install the {{Pkg|keychain}} and {{Pkg|x11-ssh-askpass}} packages.<br />
<br />
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.<br />
<br />
{{hc|~/.xinitrc|<br />
keychain ~/.ssh/id_ecdsa<br />
[ -f ~/.keychain/$HOSTNAME-sh ] && . ~/.keychain/$HOSTNAME-sh 2>/dev/null<br />
[ -f ~/.keychain/$HOSTNAME-sh-gpg ] && . ~/.keychain/$HOSTNAME-sh-gpg 2>/dev/null<br />
...<br />
exec openbox-session}}<br />
<br />
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''.<br />
<br />
==== Calling x11-ssh-askpass with ssh-add ====<br />
<br />
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:<br />
<br />
$ ln -sv /usr/lib/ssh/x11-ssh-askpass ~/bin/ssh-askpass<br />
<br />
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:<br />
<br />
$ export SSH_ASKPASS=ssh-askpass<br />
<br />
and your [[X resources]] will contain something like:<br />
<br />
ssh-askpass*background: #000000<br />
<br />
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.<br />
<br />
==== Theming ====<br />
<br />
The appearance of the ''x11-ssh-askpass'' dialog can be customized by setting its associated [[X resources]]. Some examples are the .ad files at https://github.com/sigmavirus24/x11-ssh-askpass. See {{man|1|x11-ssh-askpass}} for full details.<br />
<br />
==== Alternative passphrase dialogs ====<br />
<br />
There are other passphrase dialog programs which can be used instead of ''x11-ssh-askpass''. The following list provides some alternative solutions.<br />
<br />
* {{Pkg|ksshaskpass}} uses the [[KDE Wallet]].<br />
* {{AUR|openssh-askpass}} uses the [[Qt]] library.<br />
* {{Pkg|lxqt-openssh-askpass}}<br />
<br />
=== pam_ssh ===<br />
<br />
The [http://pam-ssh.sourceforge.net/ pam_ssh] project exists to provide a [[Pluggable Authentication Module]] (PAM) for SSH private keys. This module can provide single sign-on behavior for your SSH connections. On login, your SSH private key passphrase can be entered in place of, or in addition to, your traditional system password. Once you have been authenticated, the pam_ssh module spawns ssh-agent to store your decrypted private key for the duration of the session.<br />
<br />
To enable single sign-on behavior at the tty login prompt, install the unofficial {{AUR|pam_ssh}} package. <br />
<br />
{{Note|pam_ssh 2.0 now requires that all private keys used in the authentication process be located under {{ic|~/.ssh/login-keys.d/}}.}}<br />
<br />
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.<br />
<br />
$ mkdir ~/.ssh/login-keys.d/<br />
$ cd ~/.ssh/login-keys.d/<br />
$ ln -s ../id_rsa<br />
<br />
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.<br />
<br />
{{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 [https://developer.ibm.com/tutorials/l-pam/ article] is available which explains PAM configuration in further detail.}}<br />
<br />
{{hc|/etc/pam.d/login|2=<br />
#%PAM-1.0<br />
<br />
auth required pam_securetty.so<br />
auth requisite pam_nologin.so<br />
auth include system-local-login<br />
'''auth optional pam_ssh.so try_first_pass'''<br />
account include system-local-login<br />
session include system-local-login<br />
'''session optional pam_ssh.so'''<br />
}}<br />
<br />
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}} directory. The {{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.<br />
<br />
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.<br />
<br />
Further details on how to use pam_ssh and a list of its options can be found in the {{man|8|pam_ssh|url=}} man page.<br />
<br />
==== Using a different password to unlock the SSH key ====<br />
<br />
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<br />
<br />
{{hc|/etc/pam.d/system-auth|2=<br />
#%PAM-1.0<br />
<br />
'''auth [success=1 new_authtok_reqd=1 ignore=ignore default=ignore] pam_unix.so try_first_pass nullok'''<br />
'''auth required pam_ssh.so use_first_pass'''<br />
auth optional pam_permit.so<br />
auth required pam_env.so<br />
<br />
account required pam_unix.so<br />
account optional pam_permit.so<br />
account required pam_time.so<br />
<br />
password required pam_unix.so try_first_pass nullok sha512 shadow<br />
password optional pam_permit.so<br />
<br />
session required pam_limits.so<br />
session required pam_unix.so<br />
session optional pam_permit.so<br />
'''session optional pam_ssh.so'''<br />
}}<br />
<br />
For an explanation, see [https://unix.stackexchange.com/a/239486].<br />
<br />
==== Known issues with pam_ssh ====<br />
<br />
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.<br />
<br />
* 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.<br />
<br />
* 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.<br />
<br />
=== pam_exec-ssh ===<br />
<br />
As an alternative to [[#pam_ssh|pam_ssh]] you can use {{AUR|pam_exec-ssh}}. It is a shell script that uses pam_exec. Help for configuration can be found [https://github.com/x70b1/pam_exec-ssh upstream].<br />
<br />
=== GNOME Keyring ===<br />
<br />
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.<br />
<br />
=== Store SSH keys with Kwallet ===<br />
<br />
For instructions on how to use kwallet to store your SSH keys, see [[KDE Wallet#Using the KDE Wallet to store ssh key passphrases]].<br />
<br />
=== KeePass2 with KeeAgent plugin ===<br />
<br />
[https://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.<br />
<br />
* Supports both PuTTY and OpenSSH private key formats.<br />
* Works with native SSH agent on Linux/Mac and with PuTTY on Windows.<br />
<br />
See [[KeePass#Plugin installation in KeePass]] or [[install]] the {{Pkg|keepass-plugin-keeagent}} package.<br />
<br />
This agent can be used directly, by matching KeeAgent socket: {{ic|KeePass -> Tools -> Options -> KeeAgent -> Agent mode socket file -> %XDG_RUNTIME_DIR%/keeagent.socket}}-<br />
and environment variable:<br />
{{ic|1=export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR"'/keeagent.socket'}}.<br />
<br />
=== KeePassXC ===<br />
<br />
The KeePassXC fork of KeePass [https://keepassxc.org/docs/#faq-ssh-agent-how can act as a client for an existing SSH agent]. SSH keys stored in its database can be automatically (or manually) added to the agent. It is also compatible with KeeAgent's database format.<br />
<br />
== Troubleshooting ==<br />
<br />
=== Key ignored by the server ===<br />
<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:<br />
<br />
$ chmod 700 ~/.ssh<br />
$ chmod 600 ~/.ssh/''key''<br />
<br />
:For the remote machine:<br />
<br />
$ chmod 700 ~/.ssh<br />
$ chmod 600 ~/.ssh/authorized_keys<br />
<br />
: For the remote machine, also check that the target user's home directory has the correct permissions (it must ''not'' be writable by the group and others):<br />
<br />
$ chmod go-w /home/''target_user''<br />
<br />
* If that does not solve the problem you may try temporarily setting {{ic|StrictModes}} to {{ic|no}} in {{ic|/etc/ssh/sshd_config}}. If authentication with {{ic|StrictModes off}} is successful, it is likely an issue with file permissions persists.<br />
<br />
* Make sure keys in {{ic|~/.ssh/authorized_keys}} are entered correctly and only use one single line.<br />
* Make sure the remote machine supports the type of keys you are using: some servers do not support ECDSA keys, try using RSA or DSA keys instead, see [[#Generating an SSH key pair]].<br />
* You may want to use debug mode and monitor the output while connecting:<br />
<br />
# /usr/bin/sshd -d<br />
<br />
* If you gave another name to your key, for example {{ic|id_rsa_server}}, you need to connect with the {{ic|-i}} option:<br />
<br />
$ ssh -i id_rsa_server user@server<br />
<br />
== See also ==<br />
<br />
* OpenSSH key management: [[Funtoo:OpenSSH Key Management, Part 1|Part 1]], [[Funtoo:OpenSSH Key Management, Part 2|Part 2]], [[Funtoo:OpenSSH Key Management, Part 3|Part 3]]<br />
* [https://stribika.github.io/2015/01/04/secure-secure-shell.html Secure Secure Shell]</div>Fethbitahttps://wiki.archlinux.org/index.php?title=SSH_keys&diff=731845SSH keys2022-06-06T13:58:38Z<p>Fethbita: Add .pam_environment option for SSH_AUTH_SOCK and the reasoning behind it.</p>
<hr />
<div>[[Category:Secure Shell]]<br />
[[es:SSH keys]]<br />
[[ja:SSH 鍵]]<br />
[[zh-hans:SSH keys]]<br />
{{Expansion|The intro and ''Background'' section ignore the server perspective.}}<br />
<br />
SSH keys can 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]]. The major advantage of key-based authentication is that, in contrast to password authentication, it is not prone to [[Wikipedia:Brute-force attack|brute-force attacks]], and you do not expose valid credentials if the server has been compromised (see [[RFC:4251#section-9.4.4|RFC 4251 9.4.4]]).<br />
<br />
Furthermore, 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.<br />
<br />
Key-based authentication is not without its drawbacks and may not be appropriate for all environments, but in many circumstances it 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. <br />
<br />
This article assumes you already have a basic understanding of the [[Secure Shell]] protocol and have [[install]]ed the {{Pkg|openssh}} package.<br />
<br />
== Background ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
This [[Wikipedia:Challenge-response authentication|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.<br />
<br />
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.<br />
<br />
== Generating an SSH key pair ==<br />
<br />
An SSH key pair can be generated by running the {{ic|ssh-keygen}} command, defaulting to 3072-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:<br />
<br />
{{hc<br />
|$ ssh-keygen<br />
|<nowiki>Generating public/private rsa key pair.<br />
Enter file in which to save the key (/home/<username>/.ssh/id_rsa): <br />
Enter passphrase (empty for no passphrase): <br />
Enter same passphrase again: <br />
Your identification has been saved in /home/<username>/.ssh/id_rsa.<br />
Your public key has been saved in /home/<username>/.ssh/id_rsa.pub.<br />
The key fingerprint is:<br />
SHA256:gGJtSsV8BM+7w018d39Ji57F8iO6c0N2GZq3/RY2NhI username@hostname<br />
The key's randomart image is:<br />
+---[RSA 3072]----+<br />
| ooo. |<br />
| oo+. |<br />
| + +.+ |<br />
| o + + E . |<br />
| . . S . . =.o|<br />
| . + . . B+@o|<br />
| + . oo*=O|<br />
| . ..+=o+|<br />
| o=ooo+|<br />
+----[SHA256]-----+</nowiki>}}<br />
<br />
The [https://www.cs.berkeley.edu/~dawnsong/papers/randomart.pdf randomart image] was [https://www.openssh.com/txt/release-5.1 introduced in OpenSSH 5.1] as an easier means of visually identifying the key fingerprint.<br />
<br />
{{Note|You can use the {{ic|-a}} switch to specify the number of KDF rounds on the password encryption.}}<br />
<br />
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:<br />
<br />
$ ssh-keygen -C "$(whoami)@$(uname -n)-$(date -I)"<br />
<br />
will add a comment saying which user created the key on which machine and when.<br />
<br />
=== Choosing the authentication key type ===<br />
<br />
OpenSSH supports several signing algorithms (for authentication keys) which can be divided in two groups depending on the mathematical properties they exploit:<br />
<br />
# [[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,<br />
# [[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/content/certicom/en/52-the-elliptic-curve-discrete-logarithm-problem.html example])<br />
<br />
[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.<br />
<br />
OpenSSH 7.0 [https://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.<br />
<br />
[[#RSA]] keys will give you the greatest portability, while [[#Ed25519]] will give you the best security but requires recent versions of client & server[https://web.archive.org/web/20191222003107/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).<br />
<br />
{{Note|These keys are used only to authenticate you; choosing stronger keys will not increase CPU load when transferring data over SSH.<br />
}}<br />
<br />
==== RSA ====<br />
<br />
{{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.<br />
<br />
Minimum key size is 1024 bits, default is 3072 (see {{man|1|ssh-keygen}}) and maximum is 16384.<br />
<br />
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:<br />
<br />
$ ssh-keygen -b 4096<br />
<br />
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]<br />
<br />
On the other hand, the latest iteration of the [https://web.archive.org/web/20160305203915/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''".[https://www.keylength.com/en/6/]<br />
<br />
==== ECDSA ====<br />
<br />
The Elliptic Curve Digital Signature Algorithm (ECDSA) was introduced as the preferred algorithm for authentication [https://www.openssh.com/txt/release-5.7 in OpenSSH 5.7]. Some vendors also disable the required implementations due to potential patent issues.<br />
<br />
There are two sorts of concerns with it:<br />
<br />
# ''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] [https://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] [https://www.scientificamerican.com/article/nsa-nist-encryption-scandal/ proven] in the past.<br />
# ''Technical concerns'', about the [https://blog.cr.yp.to/20140323-ecdsa.html difficulty to properly implement the standard] and the [https://www.gossamer-threads.com/lists/openssh/dev/57162#57162 slowness and design flaws] which reduce security in insufficiently precautious implementations. <br />
<br />
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.<br />
<br />
==== Ed25519 ====<br />
<br />
[https://ed25519.cr.yp.to/ Ed25519] was introduced in [https://www.openssh.com/txt/release-6.5 OpenSSH 6.5] of January 2014: "''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.<br />
<br />
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.<br />
<br />
Ed25519 key pairs can be generated with:<br />
<br />
$ ssh-keygen -t ed25519<br />
<br />
There is no need to set the key size, as all Ed25519 keys are 256 bits.<br />
<br />
Keep in mind that older SSH clients and servers may not support these keys.<br />
<br />
==== FIDO/U2F ====<br />
<br />
FIDO/[[U2F]] [[Wikipedia:Security token|hardware authenticator]] support was added in [https://www.openssh.com/txt/release-8.2 OpenSSH version 8.2] for both of the elliptic curve signature schemes mentioned above. It allows for a hardware token attached via USB or other means to act a second factor alongside the private key. <br />
<br />
{{Note|Both the client and server must support the {{ic|ed25519-sk}} and {{ic|ecdsa-sk}} key types.}}<br />
<br />
The {{Pkg|libfido2}} is required for hardware token support.<br />
<br />
{{Note|OpenSSH uses a middleware library to communicate with the hardware token and comes with an internal middleware which supports USB tokens. Other middleware may be specified by the {{man|5|sshd_config|SecurityKeyProvider}} directive or the {{ic|SSH_SK_PROVIDER}} environment variable for {{ic|ssh-keygen}} and {{ic|ssh-add}}.}}<br />
<br />
After attaching a compatible FIDO key, a key pair may be generated with:<br />
<br />
$ ssh-keygen -t ed25519-sk<br />
<br />
You will usually be required to enter your PIN and/or tap your token to confirm the generation. Connecting to a server will usually require tapping your token unless the {{ic|-O no-touch-required}} command line option is used during generation and the {{man|8|sshd|no-touch-required}} {{ic|authorized_keys}} option is set on the server.<br />
<br />
To create keys that do not require touch events, generate a key pair with the {{ic|no-touch-required}} option. For example:<br />
<br />
$ ssh-keygen -O no-touch-required -t ed25519-sk<br />
<br />
{{Note|Not all hardware tokens support this option. If you are using a YubiKey, firmware version 5.2.3 is needed for the ed25519-sk key type.[https://www.yubico.com/blog/whats-new-in-yubikey-firmware-5-2-3/]}}<br />
<br />
Additionally, {{ic|sshd}} rejects {{ic|no-touch-required}} keys by default. To allow keys generated with this option, either enable it for an individual key in the {{ic|authorized_keys}} file,<br />
<br />
no-touch-required sk-ssh-ed25519@openssh.com AAAAInN... user@example.com<br />
<br />
or for the whole system by editing {{ic|/etc/ssh/sshd_config}} with<br />
<br />
PubkeyAuthOptions none<br />
<br />
An ECDSA-based keypair may also be generated with the {{ic|ecdsa-sk}} keytype, but the relevant concerns in the [[#ECDSA]] section above still apply.<br />
<br />
$ ssh-keygen -t ecdsa-sk<br />
<br />
=== Choosing the key location and passphrase ===<br />
<br />
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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
{{Note|Previously, the private key password was encoded in an insecure way: only a single round of an MD5 hash. OpenSSH 6.5 and later support a new, more secure format to encode your private key. This format is the default since [https://www.openssh.com/txt/release-7.8 OpenSSH version 7.8]. Ed25519 keys have always used the new encoding format. To upgrade to the new format, simply change the key's passphrase, as described in the next section.}}<br />
<br />
==== Changing the private key's passphrase without changing the key ====<br />
<br />
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. This can also be used to change the password encoding format to the new standard.<br />
<br />
$ ssh-keygen -f ~/.ssh/id_rsa -p<br />
<br />
==== Managing multiple keys ====<br />
<br />
If you have multiple SSH identities, you can set different keys to be used for different hosts or remote users by using the {{ic|Match}} and {{ic|IdentityFile}} directives in your configuration:<br />
<br />
{{hc|~/.ssh/config|2=<br />
Match host=SERVER1<br />
IdentitiesOnly yes<br />
IdentityFile ~/.ssh/id_rsa_IDENTITY1<br />
<br />
Match host=SERVER2,SERVER3<br />
IdentitiesOnly yes<br />
IdentityFile ~/.ssh/id_ed25519_IDENTITY2<br />
}}<br />
<br />
See {{man|5|ssh_config}} for full description of these options.<br />
<br />
==== Storing SSH keys on hardware tokens ====<br />
<br />
{{Expansion|[https://www.openssh.com/txt/release-8.2 OpenSSH version 8.2] adds support for FIDO2 resident keys, allowing SSH Keys to be stored on the hardware token.}}<br />
<br />
SSH keys can also be stored on a security token like a smart card or a USB token. This has the advantage that the private key is stored securely on the token instead of being stored on disk. When using a security token the sensitive private key is also never present in the RAM of the PC; the cryptographic operations are performed on the token itself. A cryptographic token has the additional advantage that it is not bound to a single computer; it can easily be removed from the computer and carried around to be used on other computers.<br />
<br />
Examples are hardware tokens are described in:<br />
<br />
* [[YubiKey#SSH notes]] Native OpenSSH support for FIDO/U2F keys<br />
* [[YubiKey#SSH keys]]<br />
* [[Trusted Platform Module#Securing SSH keys]]<br />
<br />
== Copying the public key to the remote server ==<br />
<br />
{{Expansion|How to do this if you [[OpenSSH#Force public key authentication|force public key authentication]]?}}<br />
<br />
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.<br />
<br />
=== Simple method ===<br />
<br />
{{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].}}<br />
<br />
If your key file is {{ic|~/.ssh/id_rsa.pub}} you can simply enter the following command.<br />
<br />
$ ssh-copy-id remote-server.org<br />
<br />
If your username differs on remote machine, be sure to prepend the username followed by {{ic|@}} to the server name.<br />
<br />
$ ssh-copy-id username@remote-server.org<br />
<br />
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.<br />
<br />
$ ssh-copy-id -i ~/.ssh/id_ed25519.pub username@remote-server.org<br />
<br />
If the ssh server is listening on a port other than default of 22, be sure to include it within the host argument.<br />
<br />
$ ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 221 username@remote-server.org<br />
<br />
=== Manual method ===<br />
<br />
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.<br />
<br />
$ scp ~/.ssh/id_ecdsa.pub username@remote-server.org:<br />
<br />
The above example copies the public key ({{ic|id_ecdsa.pub}}) to your home directory on the remote server via {{ic|scp}}. Do not forget to include the {{ic|:}} at the end of the server address. Also note that the name of your public key may differ from the example given.<br />
<br />
On the remote server, you will need to create the {{ic|~/.ssh}} directory if it does not yet exist and append your public key to the {{ic|authorized_keys}} file.<br />
<br />
$ ssh username@remote-server.org<br />
username@remote-server.org's password:<br />
$ mkdir ~/.ssh<br />
$ chmod 700 ~/.ssh<br />
$ cat ~/id_ecdsa.pub >> ~/.ssh/authorized_keys<br />
$ rm ~/id_ecdsa.pub<br />
$ chmod 600 ~/.ssh/authorized_keys<br />
<br />
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.<br />
<br />
== SSH agents ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
=== ssh-agent ===<br />
<br />
{{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.<br />
<br />
{{hc|$ ssh-agent|2=<br />
SSH_AUTH_SOCK=/tmp/ssh-vEGjCM2147/agent.2147; export SSH_AUTH_SOCK;<br />
SSH_AGENT_PID=2148; export SSH_AGENT_PID;<br />
echo Agent pid 2148;<br />
}}<br />
<br />
To make use of these variables, run the command through the {{ic|eval}} command.<br />
<br />
{{hc|$ eval $(ssh-agent)|<br />
Agent pid 2157<br />
}}<br />
<br />
Once {{ic|ssh-agent}} is running, you will need to add your private key to its cache:<br />
<br />
{{hc|$ ssh-add ~/.ssh/id_ed25519|<br />
Enter passphrase for /home/user/.ssh/id_ed25519:<br />
Identity added: /home/user/.ssh/id_ed25519 (/home/user/.ssh/id_ed25519)<br />
}}<br />
<br />
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 your passphrase.<br />
<br />
{{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).}}<br />
<br />
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}}:<br />
<br />
{{bc|<nowiki><br />
if ! pgrep -u "$USER" ssh-agent > /dev/null; then<br />
ssh-agent -t 1h > "$XDG_RUNTIME_DIR/ssh-agent.env"<br />
fi<br />
if [[ ! "$SSH_AUTH_SOCK" ]]; then<br />
source "$XDG_RUNTIME_DIR/ssh-agent.env" >/dev/null<br />
fi<br />
</nowiki>}}<br />
<br />
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. The lifetime of the unlocked keys is set to 1 hour.<br />
<br />
There also exist a number of front-ends to {{ic|ssh-agent}} and alternative agents described later in this section which avoid this problem.<br />
<br />
==== Start ssh-agent with systemd user ====<br />
<br />
It is possible to use the [[systemd/User]] facilities to start the agent. Use this if you would like your ssh agent to run when you are logged in, regardless of whether x is running.<br />
<br />
{{hc|~/.config/systemd/user/ssh-agent.service|2=<br />
[Unit]<br />
Description=SSH key agent<br />
<br />
[Service]<br />
Type=simple<br />
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket<br />
# DISPLAY required for ssh-askpass to work<br />
Environment=DISPLAY=:0<br />
ExecStart=/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then ''export'' the [[environment variable]] {{ic|1=SSH_AUTH_SOCK="${XDG_RUNTIME_DIR}/ssh-agent.socket"}} in your [[login shell]] initialization file, such as {{ic|~/.bash_profile}} or {{ic|~/.zprofile}} or set {{ic|1=SSH_AUTH_SOCK DEFAULT="${XDG_RUNTIME_DIR}/ssh-agent.socket"}} in {{ic|~/.pam_environment}} file, this allows the SSH_AUTH_SOCK to be set before the login shell, it is also helpful if [[Tmux#Autostart_with_systemd]] is used with [[Systemd/User]] so that the variable is set before the service.<br />
<br />
Finally, [[enable]] or [[start]] the service with the {{ic|--user}} flag.<br />
<br />
{{Note|<br />
* If you use GNOME, this environment variable is overridden by default. See [[GNOME/Keyring#Disable keyring daemon components]].<br />
* Make sure to not overwrite an existing {{ic|SSH_AUTH_SOCK}} if you want to be able to use a [[OpenSSH#Agent forwarding|forwarded ssh agent]].<br />
}}<br />
<br />
{{Tip|When starting the agent via systemd as described above, it is possible to automatically enter the passphrase of your default key and add it to the agent. See [https://github.com/capocasa/systemd-user-pam-ssh systemd-user-pam-ssh] for details.}}<br />
<br />
==== ssh-agent as a wrapper program ====<br />
<br />
An alternative way to start ssh-agent (with, say, each X session) is described in [https://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:<br />
<br />
$ ssh-agent startx<br />
<br />
And so you do not even need to think about it you can put an alias in your {{ic|.bash_aliases}} file or equivalent:<br />
<br />
alias startx='ssh-agent startx'<br />
<br />
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.<br />
<br />
{{Note|{{ic|ssh-askpass}} requires the {{ic|DISPLAY}} environment variable to work, so you may want to run {{ic|ssh-agent}} in {{ic|~/.xinitrc}} instead of {{ic|ssh-agent startx}}, where {{ic|DISPLAY}} is set. For example, you can add {{ic|exec ssh-agent dbus-launch i3}} to {{ic|~/.xinitrc}}. Or as an alternative to using {{ic|ssh-agent}} as a wrapper program, you can add {{ic|eval $(ssh-agent)}} to {{ic|~/.xinitrc}}.}}<br />
<br />
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.<br />
<br />
=== GnuPG Agent ===<br />
<br />
The [[gpg-agent]] has OpenSSH Agent protocol emulation. See [[GnuPG#SSH agent]] for necessary configuration.<br />
<br />
=== Keychain ===<br />
<br />
[[Funtoo: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.<br />
<br />
==== Installation ====<br />
<br />
[[Install]] the {{Pkg|keychain}} package.<br />
<br />
==== Configuration ====<br />
<br />
{{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.}}<br />
<br />
Add a line similar to the following to your [[shell]] configuration file, ''e.g.'' if using [[Bash]]:<br />
<br />
{{hc|~/.bashrc|<br />
eval $(keychain --eval --quiet id_ed25519 id_rsa ~/.keys/my_custom_key)<br />
}}<br />
<br />
{{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.}}<br />
<br />
In the above example,<br />
* the {{ic|--eval}} switch outputs lines to be evaluated by the opening {{ic|eval}} command; this sets the necessary environment variables for an SSH client to be able to find your agent.<br />
* {{ic|--quiet}} will limit output to warnings, errors, and user prompts.<br />
<br />
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.<br />
<br />
See {{ic|keychain --help}} or {{man|1|keychain}} for details on setting ''keychain'' for other shells.<br />
<br />
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.<br />
<br />
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.<br />
<br />
==== Tips ====<br />
<br />
* ''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).<br />
<br />
*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.<br />
<br />
*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.<br />
<br />
{{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 {{man|1|keychain}}.}}<br />
<br />
=== x11-ssh-askpass ===<br />
<br />
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.<br />
<br />
Install the {{Pkg|keychain}} and {{Pkg|x11-ssh-askpass}} packages.<br />
<br />
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.<br />
<br />
{{hc|~/.xinitrc|<br />
keychain ~/.ssh/id_ecdsa<br />
[ -f ~/.keychain/$HOSTNAME-sh ] && . ~/.keychain/$HOSTNAME-sh 2>/dev/null<br />
[ -f ~/.keychain/$HOSTNAME-sh-gpg ] && . ~/.keychain/$HOSTNAME-sh-gpg 2>/dev/null<br />
...<br />
exec openbox-session}}<br />
<br />
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''.<br />
<br />
==== Calling x11-ssh-askpass with ssh-add ====<br />
<br />
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:<br />
<br />
$ ln -sv /usr/lib/ssh/x11-ssh-askpass ~/bin/ssh-askpass<br />
<br />
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:<br />
<br />
$ export SSH_ASKPASS=ssh-askpass<br />
<br />
and your [[X resources]] will contain something like:<br />
<br />
ssh-askpass*background: #000000<br />
<br />
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.<br />
<br />
==== Theming ====<br />
<br />
The appearance of the ''x11-ssh-askpass'' dialog can be customized by setting its associated [[X resources]]. Some examples are the .ad files at https://github.com/sigmavirus24/x11-ssh-askpass. See {{man|1|x11-ssh-askpass}} for full details.<br />
<br />
==== Alternative passphrase dialogs ====<br />
<br />
There are other passphrase dialog programs which can be used instead of ''x11-ssh-askpass''. The following list provides some alternative solutions.<br />
<br />
* {{Pkg|ksshaskpass}} uses the [[KDE Wallet]].<br />
* {{AUR|openssh-askpass}} uses the [[Qt]] library.<br />
* {{Pkg|lxqt-openssh-askpass}}<br />
<br />
=== pam_ssh ===<br />
<br />
The [http://pam-ssh.sourceforge.net/ pam_ssh] project exists to provide a [[Pluggable Authentication Module]] (PAM) for SSH private keys. This module can provide single sign-on behavior for your SSH connections. On login, your SSH private key passphrase can be entered in place of, or in addition to, your traditional system password. Once you have been authenticated, the pam_ssh module spawns ssh-agent to store your decrypted private key for the duration of the session.<br />
<br />
To enable single sign-on behavior at the tty login prompt, install the unofficial {{AUR|pam_ssh}} package. <br />
<br />
{{Note|pam_ssh 2.0 now requires that all private keys used in the authentication process be located under {{ic|~/.ssh/login-keys.d/}}.}}<br />
<br />
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.<br />
<br />
$ mkdir ~/.ssh/login-keys.d/<br />
$ cd ~/.ssh/login-keys.d/<br />
$ ln -s ../id_rsa<br />
<br />
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.<br />
<br />
{{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 [https://developer.ibm.com/tutorials/l-pam/ article] is available which explains PAM configuration in further detail.}}<br />
<br />
{{hc|/etc/pam.d/login|2=<br />
#%PAM-1.0<br />
<br />
auth required pam_securetty.so<br />
auth requisite pam_nologin.so<br />
auth include system-local-login<br />
'''auth optional pam_ssh.so try_first_pass'''<br />
account include system-local-login<br />
session include system-local-login<br />
'''session optional pam_ssh.so'''<br />
}}<br />
<br />
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}} directory. The {{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.<br />
<br />
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.<br />
<br />
Further details on how to use pam_ssh and a list of its options can be found in the {{man|8|pam_ssh|url=}} man page.<br />
<br />
==== Using a different password to unlock the SSH key ====<br />
<br />
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<br />
<br />
{{hc|/etc/pam.d/system-auth|2=<br />
#%PAM-1.0<br />
<br />
'''auth [success=1 new_authtok_reqd=1 ignore=ignore default=ignore] pam_unix.so try_first_pass nullok'''<br />
'''auth required pam_ssh.so use_first_pass'''<br />
auth optional pam_permit.so<br />
auth required pam_env.so<br />
<br />
account required pam_unix.so<br />
account optional pam_permit.so<br />
account required pam_time.so<br />
<br />
password required pam_unix.so try_first_pass nullok sha512 shadow<br />
password optional pam_permit.so<br />
<br />
session required pam_limits.so<br />
session required pam_unix.so<br />
session optional pam_permit.so<br />
'''session optional pam_ssh.so'''<br />
}}<br />
<br />
For an explanation, see [https://unix.stackexchange.com/a/239486].<br />
<br />
==== Known issues with pam_ssh ====<br />
<br />
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.<br />
<br />
* 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.<br />
<br />
* 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.<br />
<br />
=== pam_exec-ssh ===<br />
<br />
As an alternative to [[#pam_ssh|pam_ssh]] you can use {{AUR|pam_exec-ssh}}. It is a shell script that uses pam_exec. Help for configuration can be found [https://github.com/x70b1/pam_exec-ssh upstream].<br />
<br />
=== GNOME Keyring ===<br />
<br />
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.<br />
<br />
=== Store SSH keys with Kwallet ===<br />
<br />
For instructions on how to use kwallet to store your SSH keys, see [[KDE Wallet#Using the KDE Wallet to store ssh key passphrases]].<br />
<br />
=== KeePass2 with KeeAgent plugin ===<br />
<br />
[https://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.<br />
<br />
* Supports both PuTTY and OpenSSH private key formats.<br />
* Works with native SSH agent on Linux/Mac and with PuTTY on Windows.<br />
<br />
See [[KeePass#Plugin installation in KeePass]] or [[install]] the {{Pkg|keepass-plugin-keeagent}} package.<br />
<br />
This agent can be used directly, by matching KeeAgent socket: {{ic|KeePass -> Tools -> Options -> KeeAgent -> Agent mode socket file -> %XDG_RUNTIME_DIR%/keeagent.socket}}-<br />
and environment variable:<br />
{{ic|1=export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR"'/keeagent.socket'}}.<br />
<br />
=== KeePassXC ===<br />
<br />
The KeePassXC fork of KeePass [https://keepassxc.org/docs/#faq-ssh-agent-how can act as a client for an existing SSH agent]. SSH keys stored in its database can be automatically (or manually) added to the agent. It is also compatible with KeeAgent's database format.<br />
<br />
== Troubleshooting ==<br />
<br />
=== Key ignored by the server ===<br />
<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:<br />
<br />
$ chmod 700 ~/.ssh<br />
$ chmod 600 ~/.ssh/''key''<br />
<br />
:For the remote machine:<br />
<br />
$ chmod 700 ~/.ssh<br />
$ chmod 600 ~/.ssh/authorized_keys<br />
<br />
: For the remote machine, also check that the target user's home directory has the correct permissions (it must ''not'' be writable by the group and others):<br />
<br />
$ chmod go-w /home/''target_user''<br />
<br />
* If that does not solve the problem you may try temporarily setting {{ic|StrictModes}} to {{ic|no}} in {{ic|/etc/ssh/sshd_config}}. If authentication with {{ic|StrictModes off}} is successful, it is likely an issue with file permissions persists.<br />
<br />
* Make sure keys in {{ic|~/.ssh/authorized_keys}} are entered correctly and only use one single line.<br />
* Make sure the remote machine supports the type of keys you are using: some servers do not support ECDSA keys, try using RSA or DSA keys instead, see [[#Generating an SSH key pair]].<br />
* You may want to use debug mode and monitor the output while connecting:<br />
<br />
# /usr/bin/sshd -d<br />
<br />
* If you gave another name to your key, for example {{ic|id_rsa_server}}, you need to connect with the {{ic|-i}} option:<br />
<br />
$ ssh -i id_rsa_server user@server<br />
<br />
== See also ==<br />
<br />
* OpenSSH key management: [[Funtoo:OpenSSH Key Management, Part 1|Part 1]], [[Funtoo:OpenSSH Key Management, Part 2|Part 2]], [[Funtoo:OpenSSH Key Management, Part 3|Part 3]]<br />
* [https://stribika.github.io/2015/01/04/secure-secure-shell.html Secure Secure Shell]</div>Fethbitahttps://wiki.archlinux.org/index.php?title=SSH_keys&diff=731844SSH keys2022-06-06T13:57:41Z<p>Fethbita: Undo revision 731843 by Fethbita (talk) restored the accidental deletion of the page</p>
<hr />
<div>[[Category:Secure Shell]]<br />
[[es:SSH keys]]<br />
[[ja:SSH 鍵]]<br />
[[zh-hans:SSH keys]]<br />
{{Expansion|The intro and ''Background'' section ignore the server perspective.}}<br />
<br />
SSH keys can 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]]. The major advantage of key-based authentication is that, in contrast to password authentication, it is not prone to [[Wikipedia:Brute-force attack|brute-force attacks]], and you do not expose valid credentials if the server has been compromised (see [[RFC:4251#section-9.4.4|RFC 4251 9.4.4]]).<br />
<br />
Furthermore, 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.<br />
<br />
Key-based authentication is not without its drawbacks and may not be appropriate for all environments, but in many circumstances it 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. <br />
<br />
This article assumes you already have a basic understanding of the [[Secure Shell]] protocol and have [[install]]ed the {{Pkg|openssh}} package.<br />
<br />
== Background ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
This [[Wikipedia:Challenge-response authentication|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.<br />
<br />
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.<br />
<br />
== Generating an SSH key pair ==<br />
<br />
An SSH key pair can be generated by running the {{ic|ssh-keygen}} command, defaulting to 3072-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:<br />
<br />
{{hc<br />
|$ ssh-keygen<br />
|<nowiki>Generating public/private rsa key pair.<br />
Enter file in which to save the key (/home/<username>/.ssh/id_rsa): <br />
Enter passphrase (empty for no passphrase): <br />
Enter same passphrase again: <br />
Your identification has been saved in /home/<username>/.ssh/id_rsa.<br />
Your public key has been saved in /home/<username>/.ssh/id_rsa.pub.<br />
The key fingerprint is:<br />
SHA256:gGJtSsV8BM+7w018d39Ji57F8iO6c0N2GZq3/RY2NhI username@hostname<br />
The key's randomart image is:<br />
+---[RSA 3072]----+<br />
| ooo. |<br />
| oo+. |<br />
| + +.+ |<br />
| o + + E . |<br />
| . . S . . =.o|<br />
| . + . . B+@o|<br />
| + . oo*=O|<br />
| . ..+=o+|<br />
| o=ooo+|<br />
+----[SHA256]-----+</nowiki>}}<br />
<br />
The [https://www.cs.berkeley.edu/~dawnsong/papers/randomart.pdf randomart image] was [https://www.openssh.com/txt/release-5.1 introduced in OpenSSH 5.1] as an easier means of visually identifying the key fingerprint.<br />
<br />
{{Note|You can use the {{ic|-a}} switch to specify the number of KDF rounds on the password encryption.}}<br />
<br />
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:<br />
<br />
$ ssh-keygen -C "$(whoami)@$(uname -n)-$(date -I)"<br />
<br />
will add a comment saying which user created the key on which machine and when.<br />
<br />
=== Choosing the authentication key type ===<br />
<br />
OpenSSH supports several signing algorithms (for authentication keys) which can be divided in two groups depending on the mathematical properties they exploit:<br />
<br />
# [[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,<br />
# [[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/content/certicom/en/52-the-elliptic-curve-discrete-logarithm-problem.html example])<br />
<br />
[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.<br />
<br />
OpenSSH 7.0 [https://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.<br />
<br />
[[#RSA]] keys will give you the greatest portability, while [[#Ed25519]] will give you the best security but requires recent versions of client & server[https://web.archive.org/web/20191222003107/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).<br />
<br />
{{Note|These keys are used only to authenticate you; choosing stronger keys will not increase CPU load when transferring data over SSH.<br />
}}<br />
<br />
==== RSA ====<br />
<br />
{{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.<br />
<br />
Minimum key size is 1024 bits, default is 3072 (see {{man|1|ssh-keygen}}) and maximum is 16384.<br />
<br />
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:<br />
<br />
$ ssh-keygen -b 4096<br />
<br />
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]<br />
<br />
On the other hand, the latest iteration of the [https://web.archive.org/web/20160305203915/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''".[https://www.keylength.com/en/6/]<br />
<br />
==== ECDSA ====<br />
<br />
The Elliptic Curve Digital Signature Algorithm (ECDSA) was introduced as the preferred algorithm for authentication [https://www.openssh.com/txt/release-5.7 in OpenSSH 5.7]. Some vendors also disable the required implementations due to potential patent issues.<br />
<br />
There are two sorts of concerns with it:<br />
<br />
# ''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] [https://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] [https://www.scientificamerican.com/article/nsa-nist-encryption-scandal/ proven] in the past.<br />
# ''Technical concerns'', about the [https://blog.cr.yp.to/20140323-ecdsa.html difficulty to properly implement the standard] and the [https://www.gossamer-threads.com/lists/openssh/dev/57162#57162 slowness and design flaws] which reduce security in insufficiently precautious implementations. <br />
<br />
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.<br />
<br />
==== Ed25519 ====<br />
<br />
[https://ed25519.cr.yp.to/ Ed25519] was introduced in [https://www.openssh.com/txt/release-6.5 OpenSSH 6.5] of January 2014: "''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.<br />
<br />
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.<br />
<br />
Ed25519 key pairs can be generated with:<br />
<br />
$ ssh-keygen -t ed25519<br />
<br />
There is no need to set the key size, as all Ed25519 keys are 256 bits.<br />
<br />
Keep in mind that older SSH clients and servers may not support these keys.<br />
<br />
==== FIDO/U2F ====<br />
<br />
FIDO/[[U2F]] [[Wikipedia:Security token|hardware authenticator]] support was added in [https://www.openssh.com/txt/release-8.2 OpenSSH version 8.2] for both of the elliptic curve signature schemes mentioned above. It allows for a hardware token attached via USB or other means to act a second factor alongside the private key. <br />
<br />
{{Note|Both the client and server must support the {{ic|ed25519-sk}} and {{ic|ecdsa-sk}} key types.}}<br />
<br />
The {{Pkg|libfido2}} is required for hardware token support.<br />
<br />
{{Note|OpenSSH uses a middleware library to communicate with the hardware token and comes with an internal middleware which supports USB tokens. Other middleware may be specified by the {{man|5|sshd_config|SecurityKeyProvider}} directive or the {{ic|SSH_SK_PROVIDER}} environment variable for {{ic|ssh-keygen}} and {{ic|ssh-add}}.}}<br />
<br />
After attaching a compatible FIDO key, a key pair may be generated with:<br />
<br />
$ ssh-keygen -t ed25519-sk<br />
<br />
You will usually be required to enter your PIN and/or tap your token to confirm the generation. Connecting to a server will usually require tapping your token unless the {{ic|-O no-touch-required}} command line option is used during generation and the {{man|8|sshd|no-touch-required}} {{ic|authorized_keys}} option is set on the server.<br />
<br />
To create keys that do not require touch events, generate a key pair with the {{ic|no-touch-required}} option. For example:<br />
<br />
$ ssh-keygen -O no-touch-required -t ed25519-sk<br />
<br />
{{Note|Not all hardware tokens support this option. If you are using a YubiKey, firmware version 5.2.3 is needed for the ed25519-sk key type.[https://www.yubico.com/blog/whats-new-in-yubikey-firmware-5-2-3/]}}<br />
<br />
Additionally, {{ic|sshd}} rejects {{ic|no-touch-required}} keys by default. To allow keys generated with this option, either enable it for an individual key in the {{ic|authorized_keys}} file,<br />
<br />
no-touch-required sk-ssh-ed25519@openssh.com AAAAInN... user@example.com<br />
<br />
or for the whole system by editing {{ic|/etc/ssh/sshd_config}} with<br />
<br />
PubkeyAuthOptions none<br />
<br />
An ECDSA-based keypair may also be generated with the {{ic|ecdsa-sk}} keytype, but the relevant concerns in the [[#ECDSA]] section above still apply.<br />
<br />
$ ssh-keygen -t ecdsa-sk<br />
<br />
=== Choosing the key location and passphrase ===<br />
<br />
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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
{{Note|Previously, the private key password was encoded in an insecure way: only a single round of an MD5 hash. OpenSSH 6.5 and later support a new, more secure format to encode your private key. This format is the default since [https://www.openssh.com/txt/release-7.8 OpenSSH version 7.8]. Ed25519 keys have always used the new encoding format. To upgrade to the new format, simply change the key's passphrase, as described in the next section.}}<br />
<br />
==== Changing the private key's passphrase without changing the key ====<br />
<br />
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. This can also be used to change the password encoding format to the new standard.<br />
<br />
$ ssh-keygen -f ~/.ssh/id_rsa -p<br />
<br />
==== Managing multiple keys ====<br />
<br />
If you have multiple SSH identities, you can set different keys to be used for different hosts or remote users by using the {{ic|Match}} and {{ic|IdentityFile}} directives in your configuration:<br />
<br />
{{hc|~/.ssh/config|2=<br />
Match host=SERVER1<br />
IdentitiesOnly yes<br />
IdentityFile ~/.ssh/id_rsa_IDENTITY1<br />
<br />
Match host=SERVER2,SERVER3<br />
IdentitiesOnly yes<br />
IdentityFile ~/.ssh/id_ed25519_IDENTITY2<br />
}}<br />
<br />
See {{man|5|ssh_config}} for full description of these options.<br />
<br />
==== Storing SSH keys on hardware tokens ====<br />
<br />
{{Expansion|[https://www.openssh.com/txt/release-8.2 OpenSSH version 8.2] adds support for FIDO2 resident keys, allowing SSH Keys to be stored on the hardware token.}}<br />
<br />
SSH keys can also be stored on a security token like a smart card or a USB token. This has the advantage that the private key is stored securely on the token instead of being stored on disk. When using a security token the sensitive private key is also never present in the RAM of the PC; the cryptographic operations are performed on the token itself. A cryptographic token has the additional advantage that it is not bound to a single computer; it can easily be removed from the computer and carried around to be used on other computers.<br />
<br />
Examples are hardware tokens are described in:<br />
<br />
* [[YubiKey#SSH notes]] Native OpenSSH support for FIDO/U2F keys<br />
* [[YubiKey#SSH keys]]<br />
* [[Trusted Platform Module#Securing SSH keys]]<br />
<br />
== Copying the public key to the remote server ==<br />
<br />
{{Expansion|How to do this if you [[OpenSSH#Force public key authentication|force public key authentication]]?}}<br />
<br />
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.<br />
<br />
=== Simple method ===<br />
<br />
{{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].}}<br />
<br />
If your key file is {{ic|~/.ssh/id_rsa.pub}} you can simply enter the following command.<br />
<br />
$ ssh-copy-id remote-server.org<br />
<br />
If your username differs on remote machine, be sure to prepend the username followed by {{ic|@}} to the server name.<br />
<br />
$ ssh-copy-id username@remote-server.org<br />
<br />
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.<br />
<br />
$ ssh-copy-id -i ~/.ssh/id_ed25519.pub username@remote-server.org<br />
<br />
If the ssh server is listening on a port other than default of 22, be sure to include it within the host argument.<br />
<br />
$ ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 221 username@remote-server.org<br />
<br />
=== Manual method ===<br />
<br />
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.<br />
<br />
$ scp ~/.ssh/id_ecdsa.pub username@remote-server.org:<br />
<br />
The above example copies the public key ({{ic|id_ecdsa.pub}}) to your home directory on the remote server via {{ic|scp}}. Do not forget to include the {{ic|:}} at the end of the server address. Also note that the name of your public key may differ from the example given.<br />
<br />
On the remote server, you will need to create the {{ic|~/.ssh}} directory if it does not yet exist and append your public key to the {{ic|authorized_keys}} file.<br />
<br />
$ ssh username@remote-server.org<br />
username@remote-server.org's password:<br />
$ mkdir ~/.ssh<br />
$ chmod 700 ~/.ssh<br />
$ cat ~/id_ecdsa.pub >> ~/.ssh/authorized_keys<br />
$ rm ~/id_ecdsa.pub<br />
$ chmod 600 ~/.ssh/authorized_keys<br />
<br />
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.<br />
<br />
== SSH agents ==<br />
<br />
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.<br />
<br />
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.<br />
<br />
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.<br />
<br />
=== ssh-agent ===<br />
<br />
{{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.<br />
<br />
{{hc|$ ssh-agent|2=<br />
SSH_AUTH_SOCK=/tmp/ssh-vEGjCM2147/agent.2147; export SSH_AUTH_SOCK;<br />
SSH_AGENT_PID=2148; export SSH_AGENT_PID;<br />
echo Agent pid 2148;<br />
}}<br />
<br />
To make use of these variables, run the command through the {{ic|eval}} command.<br />
<br />
{{hc|$ eval $(ssh-agent)|<br />
Agent pid 2157<br />
}}<br />
<br />
Once {{ic|ssh-agent}} is running, you will need to add your private key to its cache:<br />
<br />
{{hc|$ ssh-add ~/.ssh/id_ed25519|<br />
Enter passphrase for /home/user/.ssh/id_ed25519:<br />
Identity added: /home/user/.ssh/id_ed25519 (/home/user/.ssh/id_ed25519)<br />
}}<br />
<br />
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 your passphrase.<br />
<br />
{{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).}}<br />
<br />
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}}:<br />
<br />
{{bc|<nowiki><br />
if ! pgrep -u "$USER" ssh-agent > /dev/null; then<br />
ssh-agent -t 1h > "$XDG_RUNTIME_DIR/ssh-agent.env"<br />
fi<br />
if [[ ! "$SSH_AUTH_SOCK" ]]; then<br />
source "$XDG_RUNTIME_DIR/ssh-agent.env" >/dev/null<br />
fi<br />
</nowiki>}}<br />
<br />
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. The lifetime of the unlocked keys is set to 1 hour.<br />
<br />
There also exist a number of front-ends to {{ic|ssh-agent}} and alternative agents described later in this section which avoid this problem.<br />
<br />
==== Start ssh-agent with systemd user ====<br />
<br />
It is possible to use the [[systemd/User]] facilities to start the agent. Use this if you would like your ssh agent to run when you are logged in, regardless of whether x is running.<br />
<br />
{{hc|~/.config/systemd/user/ssh-agent.service|2=<br />
[Unit]<br />
Description=SSH key agent<br />
<br />
[Service]<br />
Type=simple<br />
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket<br />
# DISPLAY required for ssh-askpass to work<br />
Environment=DISPLAY=:0<br />
ExecStart=/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then ''export'' the [[environment variable]] {{ic|1=SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/ssh-agent.socket"}} in your [[login shell]] initialization file, such as {{ic|~/.bash_profile}} or {{ic|~/.zprofile}}.<br />
<br />
Finally, [[enable]] or [[start]] the service with the {{ic|--user}} flag.<br />
<br />
{{Note|<br />
* If you use GNOME, this environment variable is overridden by default. See [[GNOME/Keyring#Disable keyring daemon components]].<br />
* Make sure to not overwrite an existing {{ic|SSH_AUTH_SOCK}} if you want to be able to use a [[OpenSSH#Agent forwarding|forwarded ssh agent]].<br />
}}<br />
<br />
{{Tip|When starting the agent via systemd as described above, it is possible to automatically enter the passphrase of your default key and add it to the agent. See [https://github.com/capocasa/systemd-user-pam-ssh systemd-user-pam-ssh] for details.}}<br />
<br />
==== ssh-agent as a wrapper program ====<br />
<br />
An alternative way to start ssh-agent (with, say, each X session) is described in [https://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:<br />
<br />
$ ssh-agent startx<br />
<br />
And so you do not even need to think about it you can put an alias in your {{ic|.bash_aliases}} file or equivalent:<br />
<br />
alias startx='ssh-agent startx'<br />
<br />
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.<br />
<br />
{{Note|{{ic|ssh-askpass}} requires the {{ic|DISPLAY}} environment variable to work, so you may want to run {{ic|ssh-agent}} in {{ic|~/.xinitrc}} instead of {{ic|ssh-agent startx}}, where {{ic|DISPLAY}} is set. For example, you can add {{ic|exec ssh-agent dbus-launch i3}} to {{ic|~/.xinitrc}}. Or as an alternative to using {{ic|ssh-agent}} as a wrapper program, you can add {{ic|eval $(ssh-agent)}} to {{ic|~/.xinitrc}}.}}<br />
<br />
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.<br />
<br />
=== GnuPG Agent ===<br />
<br />
The [[gpg-agent]] has OpenSSH Agent protocol emulation. See [[GnuPG#SSH agent]] for necessary configuration.<br />
<br />
=== Keychain ===<br />
<br />
[[Funtoo: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.<br />
<br />
==== Installation ====<br />
<br />
[[Install]] the {{Pkg|keychain}} package.<br />
<br />
==== Configuration ====<br />
<br />
{{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.}}<br />
<br />
Add a line similar to the following to your [[shell]] configuration file, ''e.g.'' if using [[Bash]]:<br />
<br />
{{hc|~/.bashrc|<br />
eval $(keychain --eval --quiet id_ed25519 id_rsa ~/.keys/my_custom_key)<br />
}}<br />
<br />
{{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.}}<br />
<br />
In the above example,<br />
* the {{ic|--eval}} switch outputs lines to be evaluated by the opening {{ic|eval}} command; this sets the necessary environment variables for an SSH client to be able to find your agent.<br />
* {{ic|--quiet}} will limit output to warnings, errors, and user prompts.<br />
<br />
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.<br />
<br />
See {{ic|keychain --help}} or {{man|1|keychain}} for details on setting ''keychain'' for other shells.<br />
<br />
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.<br />
<br />
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.<br />
<br />
==== Tips ====<br />
<br />
* ''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).<br />
<br />
*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.<br />
<br />
*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.<br />
<br />
{{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 {{man|1|keychain}}.}}<br />
<br />
=== x11-ssh-askpass ===<br />
<br />
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.<br />
<br />
Install the {{Pkg|keychain}} and {{Pkg|x11-ssh-askpass}} packages.<br />
<br />
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.<br />
<br />
{{hc|~/.xinitrc|<br />
keychain ~/.ssh/id_ecdsa<br />
[ -f ~/.keychain/$HOSTNAME-sh ] && . ~/.keychain/$HOSTNAME-sh 2>/dev/null<br />
[ -f ~/.keychain/$HOSTNAME-sh-gpg ] && . ~/.keychain/$HOSTNAME-sh-gpg 2>/dev/null<br />
...<br />
exec openbox-session}}<br />
<br />
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''.<br />
<br />
==== Calling x11-ssh-askpass with ssh-add ====<br />
<br />
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:<br />
<br />
$ ln -sv /usr/lib/ssh/x11-ssh-askpass ~/bin/ssh-askpass<br />
<br />
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:<br />
<br />
$ export SSH_ASKPASS=ssh-askpass<br />
<br />
and your [[X resources]] will contain something like:<br />
<br />
ssh-askpass*background: #000000<br />
<br />
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.<br />
<br />
==== Theming ====<br />
<br />
The appearance of the ''x11-ssh-askpass'' dialog can be customized by setting its associated [[X resources]]. Some examples are the .ad files at https://github.com/sigmavirus24/x11-ssh-askpass. See {{man|1|x11-ssh-askpass}} for full details.<br />
<br />
==== Alternative passphrase dialogs ====<br />
<br />
There are other passphrase dialog programs which can be used instead of ''x11-ssh-askpass''. The following list provides some alternative solutions.<br />
<br />
* {{Pkg|ksshaskpass}} uses the [[KDE Wallet]].<br />
* {{AUR|openssh-askpass}} uses the [[Qt]] library.<br />
* {{Pkg|lxqt-openssh-askpass}}<br />
<br />
=== pam_ssh ===<br />
<br />
The [http://pam-ssh.sourceforge.net/ pam_ssh] project exists to provide a [[Pluggable Authentication Module]] (PAM) for SSH private keys. This module can provide single sign-on behavior for your SSH connections. On login, your SSH private key passphrase can be entered in place of, or in addition to, your traditional system password. Once you have been authenticated, the pam_ssh module spawns ssh-agent to store your decrypted private key for the duration of the session.<br />
<br />
To enable single sign-on behavior at the tty login prompt, install the unofficial {{AUR|pam_ssh}} package. <br />
<br />
{{Note|pam_ssh 2.0 now requires that all private keys used in the authentication process be located under {{ic|~/.ssh/login-keys.d/}}.}}<br />
<br />
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.<br />
<br />
$ mkdir ~/.ssh/login-keys.d/<br />
$ cd ~/.ssh/login-keys.d/<br />
$ ln -s ../id_rsa<br />
<br />
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.<br />
<br />
{{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 [https://developer.ibm.com/tutorials/l-pam/ article] is available which explains PAM configuration in further detail.}}<br />
<br />
{{hc|/etc/pam.d/login|2=<br />
#%PAM-1.0<br />
<br />
auth required pam_securetty.so<br />
auth requisite pam_nologin.so<br />
auth include system-local-login<br />
'''auth optional pam_ssh.so try_first_pass'''<br />
account include system-local-login<br />
session include system-local-login<br />
'''session optional pam_ssh.so'''<br />
}}<br />
<br />
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}} directory. The {{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.<br />
<br />
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.<br />
<br />
Further details on how to use pam_ssh and a list of its options can be found in the {{man|8|pam_ssh|url=}} man page.<br />
<br />
==== Using a different password to unlock the SSH key ====<br />
<br />
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<br />
<br />
{{hc|/etc/pam.d/system-auth|2=<br />
#%PAM-1.0<br />
<br />
'''auth [success=1 new_authtok_reqd=1 ignore=ignore default=ignore] pam_unix.so try_first_pass nullok'''<br />
'''auth required pam_ssh.so use_first_pass'''<br />
auth optional pam_permit.so<br />
auth required pam_env.so<br />
<br />
account required pam_unix.so<br />
account optional pam_permit.so<br />
account required pam_time.so<br />
<br />
password required pam_unix.so try_first_pass nullok sha512 shadow<br />
password optional pam_permit.so<br />
<br />
session required pam_limits.so<br />
session required pam_unix.so<br />
session optional pam_permit.so<br />
'''session optional pam_ssh.so'''<br />
}}<br />
<br />
For an explanation, see [https://unix.stackexchange.com/a/239486].<br />
<br />
==== Known issues with pam_ssh ====<br />
<br />
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.<br />
<br />
* 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.<br />
<br />
* 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.<br />
<br />
=== pam_exec-ssh ===<br />
<br />
As an alternative to [[#pam_ssh|pam_ssh]] you can use {{AUR|pam_exec-ssh}}. It is a shell script that uses pam_exec. Help for configuration can be found [https://github.com/x70b1/pam_exec-ssh upstream].<br />
<br />
=== GNOME Keyring ===<br />
<br />
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.<br />
<br />
=== Store SSH keys with Kwallet ===<br />
<br />
For instructions on how to use kwallet to store your SSH keys, see [[KDE Wallet#Using the KDE Wallet to store ssh key passphrases]].<br />
<br />
=== KeePass2 with KeeAgent plugin ===<br />
<br />
[https://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.<br />
<br />
* Supports both PuTTY and OpenSSH private key formats.<br />
* Works with native SSH agent on Linux/Mac and with PuTTY on Windows.<br />
<br />
See [[KeePass#Plugin installation in KeePass]] or [[install]] the {{Pkg|keepass-plugin-keeagent}} package.<br />
<br />
This agent can be used directly, by matching KeeAgent socket: {{ic|KeePass -> Tools -> Options -> KeeAgent -> Agent mode socket file -> %XDG_RUNTIME_DIR%/keeagent.socket}}-<br />
and environment variable:<br />
{{ic|1=export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR"'/keeagent.socket'}}.<br />
<br />
=== KeePassXC ===<br />
<br />
The KeePassXC fork of KeePass [https://keepassxc.org/docs/#faq-ssh-agent-how can act as a client for an existing SSH agent]. SSH keys stored in its database can be automatically (or manually) added to the agent. It is also compatible with KeeAgent's database format.<br />
<br />
== Troubleshooting ==<br />
<br />
=== Key ignored by the server ===<br />
<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:<br />
<br />
$ chmod 700 ~/.ssh<br />
$ chmod 600 ~/.ssh/''key''<br />
<br />
:For the remote machine:<br />
<br />
$ chmod 700 ~/.ssh<br />
$ chmod 600 ~/.ssh/authorized_keys<br />
<br />
: For the remote machine, also check that the target user's home directory has the correct permissions (it must ''not'' be writable by the group and others):<br />
<br />
$ chmod go-w /home/''target_user''<br />
<br />
* If that does not solve the problem you may try temporarily setting {{ic|StrictModes}} to {{ic|no}} in {{ic|/etc/ssh/sshd_config}}. If authentication with {{ic|StrictModes off}} is successful, it is likely an issue with file permissions persists.<br />
<br />
* Make sure keys in {{ic|~/.ssh/authorized_keys}} are entered correctly and only use one single line.<br />
* Make sure the remote machine supports the type of keys you are using: some servers do not support ECDSA keys, try using RSA or DSA keys instead, see [[#Generating an SSH key pair]].<br />
* You may want to use debug mode and monitor the output while connecting:<br />
<br />
# /usr/bin/sshd -d<br />
<br />
* If you gave another name to your key, for example {{ic|id_rsa_server}}, you need to connect with the {{ic|-i}} option:<br />
<br />
$ ssh -i id_rsa_server user@server<br />
<br />
== See also ==<br />
<br />
* OpenSSH key management: [[Funtoo:OpenSSH Key Management, Part 1|Part 1]], [[Funtoo:OpenSSH Key Management, Part 2|Part 2]], [[Funtoo:OpenSSH Key Management, Part 3|Part 3]]<br />
* [https://stribika.github.io/2015/01/04/secure-secure-shell.html Secure Secure Shell]</div>Fethbitahttps://wiki.archlinux.org/index.php?title=SSH_keys&diff=731843SSH keys2022-06-06T13:56:28Z<p>Fethbita: Add .pam_environment option for SSH_AUTH_SOCK and the reasoning behind it.</p>
<hr />
<div>==== Start ssh-agent with systemd user ====<br />
<br />
It is possible to use the [[systemd/User]] facilities to start the agent. Use this if you would like your ssh agent to run when you are logged in, regardless of whether x is running.<br />
<br />
{{hc|~/.config/systemd/user/ssh-agent.service|2=<br />
[Unit]<br />
Description=SSH key agent<br />
<br />
[Service]<br />
Type=simple<br />
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket<br />
# DISPLAY required for ssh-askpass to work<br />
Environment=DISPLAY=:0<br />
ExecStart=/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK<br />
<br />
[Install]<br />
WantedBy=default.target<br />
}}<br />
<br />
Then ''export'' the [[environment variable]] {{ic|1=SSH_AUTH_SOCK="${XDG_RUNTIME_DIR}/ssh-agent.socket"}} in your [[login shell]] initialization file, such as {{ic|~/.bash_profile}} or {{ic|~/.zprofile}} or set {{ic|1=SSH_AUTH_SOCK DEFAULT="${XDG_RUNTIME_DIR}/ssh-agent.socket"}} in {{ic|~/.pam_environment}} file, this allows the SSH_AUTH_SOCK to be set before the login shell, it is also helpful if [[Tmux#Autostart_with_systemd]] is used with [[Systemd/User]] so that the variable is set before the service.<br />
<br />
Finally, [[enable]] or [[start]] the service with the {{ic|--user}} flag.<br />
<br />
{{Note|<br />
* If you use GNOME, this environment variable is overridden by default. See [[GNOME/Keyring#Disable keyring daemon components]].<br />
* Make sure to not overwrite an existing {{ic|SSH_AUTH_SOCK}} if you want to be able to use a [[OpenSSH#Agent forwarding|forwarded ssh agent]].<br />
}}<br />
<br />
{{Tip|When starting the agent via systemd as described above, it is possible to automatically enter the passphrase of your default key and add it to the agent. See [https://github.com/capocasa/systemd-user-pam-ssh systemd-user-pam-ssh] for details.}}</div>Fethbitahttps://wiki.archlinux.org/index.php?title=Tmux&diff=731349Tmux2022-06-02T14:05:40Z<p>Fethbita: Add a missing paren and make the note bold.</p>
<hr />
<div>{{Lowercase title}}<br />
[[Category:Terminal multiplexers]]<br />
[[de:Tmux]]<br />
[[ja:Tmux]]<br />
[[zh-hans:Tmux]]<br />
[https://tmux.github.io/ tmux] is a "terminal multiplexer: it enables a number of terminals (or windows), each running a separate program, to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached." <br />
<br />
tmux is an ISC-licensed alternative to [[GNU Screen]]. Although similar, there are many differences between the programs, as noted on the [https://github.com/tmux/tmux/wiki/FAQ tmux FAQ page].<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|tmux}} package.<br />
Optionally, install {{AUR|tmux-bash-completion-git}} to provide bash completion functions for tmux.<br />
<br />
== Configuration ==<br />
<br />
By default, tmux looks for user-specific configuration at {{ic|~/.tmux.conf}}, though {{ic|~/.config/tmux/tmux.conf}} (hardcoded, {{ic|$XDG_CONFIG_HOME}} is ignored) works too. A global configuration file may be provided at {{ic|/etc/tmux.conf}} though by default Arch does not ship such a file.<br />
<br />
=== Key bindings ===<br />
<br />
By default, command key bindings are prefixed by {{ic|Ctrl+b}}. For example, to vertically split a window type {{ic|Ctrl+b %}}.<br />
<br />
After splitting a window into multiple panes, a pane can be resized by the hitting prefix key (e.g. {{ic|Ctrl+b}}) and, while continuing to hold {{ic|Ctrl}}, press Left/Right/Up/Down. Swapping panes is achieved in the same manner, but by hitting ''o'' instead of a directional key.<br />
<br />
Key bindings may be changed with the bind and unbind commands in {{ic|tmux.conf}}. For example, the default prefix binding of {{ic|Ctrl+b}} can be changed to {{ic|Ctrl+a}} by adding the following commands in your configuration file:<br />
<br />
{{bc|<br />
unbind C-b<br />
set -g prefix C-a<br />
bind C-a send-prefix<br />
}}<br />
<br />
{{Tip|Quote special characters to use them as prefix. You may also use {{ic|Alt}} (called Meta) instead of {{ic|Ctrl}}. For example: {{ic|set -g prefix m-'\'}}}}<br />
<br />
To create a new window you can use {{ic|Ctrl+b c}} and move forward one window with {{ic|Ctrl+b n}} and backwards one window with {{ic|Ctrl+b p}}.<br />
<br />
Additional ways to move between windows include the following:<br />
<br />
Ctrl+b l (Move to the previously selected window)<br />
Ctrl+b w (List all windows / window numbers)<br />
Ctrl+b <window number> (Move to the specified window number, the default bindings are from 0 – 9)<br />
Ctrl+b q (Show pane numbers, when the numbers show up type the key to goto that pane)<br />
<br />
tmux has a find-window option & key binding to ease navigation of many windows:<br />
<br />
Ctrl+b f <window name> (Search for window name)<br />
Ctrl+b w (Select from interactive list of windows)<br />
<br />
==== Copy Mode ====<br />
<br />
A tmux window may be in one of several modes. The default permits direct access to the terminal attached to the window; the other is copy mode. Once in copy mode you can navigate the buffer including scrolling the history. Use [[vi]] or [[emacs]]-style key bindings in copy mode. The default is emacs, unless VISUAL or EDITOR contains ‘vi’<br />
<br />
To enter copy mode do the following:<br />
<br />
Ctrl+b [<br />
<br />
You can navigate the buffer as you would in your default editor.<br />
<br />
To quit copy mode, use one of the following keybindings:<br />
<br />
vi mode:<br />
q<br />
emacs mode:<br />
Esc<br />
<br />
=== Browsing URLs ===<br />
<br />
To browse URLs inside tmux you must have {{AUR|urlview}} installed and configured.<br />
<br />
Inside a new terminal:<br />
bind-key u capture-pane \; save-buffer /tmp/tmux-buffer \; run-shell "$TERMINAL -e urlview /tmp/tmux-buffer"<br />
<br />
Or inside a new tmux window (no new terminal needed):<br />
bind-key u capture-pane \; save-buffer /tmp/tmux-buffer \; new-window -n "urlview" '$SHELL -c "urlview < /tmp/tmux-buffer"'<br />
<br />
=== Setting the correct term ===<br />
<br />
==== 256 colors ====<br />
<br />
If you are using a 256 colour terminal, you will need to set the correct term in tmux. As of [https://raw.githubusercontent.com/tmux/tmux/master/CHANGES tmux 2.1], this is now ''tmux'', or ''tmux-256color''. You can do this in {{ic|tmux.conf}}:<br />
<br />
set -g default-terminal "tmux-256color" <br />
<br />
Other, older alternatives, include ''screen'', or ''screen-256color'':<br />
<br />
set -g default-terminal "screen-256color"<br />
<br />
Also, if tmux messes up, you can force tmux to assume that the terminal support 256 colors, by adding this in your .bashrc:<br />
<br />
alias tmux="tmux -2"<br />
<br />
==== 24-bit color ====<br />
<br />
tmux supports 24-bit color as of version 2.2 [https://github.com/tmux/tmux/commit/427b8204268af5548d09b830e101c59daa095df9]. If your terminal supports 24-bit color (see this [https://gist.github.com/XVilka/8346728 gist]), add your terminal to the {{ic|terminal-overrides}} setting. For example, if you use [[Termite]], you would add:<br />
<br />
set -ga terminal-overrides ",xterm-termite:Tc"<br />
<br />
For other terminals, replace {{ic|xterm-termite}} with the relevant terminal type (stored in {{ic|$TERM}}). See the {{man|1|tmux}} man page for details about the {{ic|Tc}} terminfo extension.<br />
<br />
==== xterm-keys ====<br />
<br />
To enable xterm-keys in your {{ic|tmux.conf}}, you have to add the following line<br />
<br />
set-option -g xterm-keys on<br />
<br />
If you enable xterm-keys in your {{ic|tmux.conf}}, then you need to build a custom terminfo to declare the new escape codes or applications will not know about them. Compile the following with {{ic|tic}} and you can use "xterm-screen-256color" as your TERM:<br />
<br />
# A screen- based TERMINFO that declares the escape sequences<br />
# enabled by the tmux config "set-window-option -g xterm-keys".<br />
#<br />
# Prefix the name with xterm- since some applications inspect<br />
# the TERM *name* in addition to the terminal capabilities advertised.<br />
xterm-screen-256color|GNU Screen with 256 colors bce and tmux xterm-keys,<br />
<br />
# As of Nov'11, the below keys are picked up by<br />
# .../tmux/blob/master/trunk/xterm-keys.c:<br />
kDC=\E[3;2~, kEND=\E[1;2F, kHOM=\E[1;2H,<br />
kIC=\E[2;2~, kLFT=\E[1;2D, kNXT=\E[6;2~, kPRV=\E[5;2~,<br />
kRIT=\E[1;2C,<br />
<br />
# Change this to screen-256color if the terminal you run tmux in<br />
# doesn't support bce:<br />
use=screen-256color-bce,<br />
<br />
To check if your terminal support bce, you can use {{ic|tic -c}}:<br />
<br />
$ tic -c xterm-screen-256color <br />
"xterm-screen-256color", line 16, terminal 'xterm-screen-256color': resolution of use=screen-256color-bce failed<br />
<br />
To compile with tic:<br />
<br />
$ tic xterm-screen-256color <br />
<br />
The file will be compiled and saved in $HOME/.terminfo or in /usr/share/terminfo/ if run as root (and so available system-wide).<br />
<br />
=== Other Settings ===<br />
<br />
To limit the scrollback buffer to 10000 lines:<br />
set -g history-limit 10000<br />
<br />
Mouse can be toggled with<br />
bind-key m set-option -g mouse \; display "Mouse: #{?mouse,ON,OFF}"<br />
<br />
=== Autostart with systemd ===<br />
<br />
There are some notable advantages to starting a tmux server at startup.<br />
Notably, when you start a new tmux session, having the service already running reduces any delays in the startup.<br />
<br />
Furthermore, any customization attached to your tmux session will be retained and your tmux session can be made to persist even if you have never logged in, if you have some reason to do that (like a heavily scripted tmux configuration or shared user tmux sessions).<br />
<br />
The service below starts ''tmux'' for the specified user (i.e. start with {{ic|tmux@''username''.service}}):<br />
<br />
{{hc|/etc/systemd/system/tmux@.service|<nowiki><br />
[Unit]<br />
Description=Start tmux in detached session<br />
<br />
[Service]<br />
Type=forking<br />
User=%I<br />
ExecStart=/usr/bin/tmux new-session -s %u -d<br />
ExecStop=/usr/bin/tmux kill-session -t %u<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
{{Tip|You may want to add {{ic|1=WorkingDirectory=''custom_path''}} to customize working directory. If set to {{ic|~}}, the home directory of the user specified in {{ic|1=User=}} is used.}}<br />
<br />
Alternatively, you can place this file within your [[systemd/User]] directory (without {{ic|1=User=%I}} and by replacing {{ic|multi-user.target}} with {{ic|default.target}} in {{ic|WantedBy}}), for example {{ic|~/.config/systemd/user/tmux.service}}. This way the tmux service will start when you log in, unless you also enable [[systemd/User#Automatic start-up of systemd user instances]].<br />
<br />
== Session initialization ==<br />
<br />
You can have tmux open a session with preloaded windows by including those details in your {{ic|~/.tmux.conf}}:<br />
<br />
new -n WindowName Command<br />
neww -n WindowName Command<br />
neww -n WindowName Command<br />
<br />
To start a session with split windows (multiple panes), include the splitw command below the neww you would like to split; thus:<br />
<br />
new -s SessionName -n WindowName Command<br />
neww -n foo/bar foo<br />
splitw -v -p 50 -t 0 bar<br />
selectw -t 1 <br />
selectp -t 0<br />
<br />
would open 2 windows, the second of which would be named foo/bar and would be split vertically in half (50%) with foo running above bar. Focus would be in window 2 (foo/bar), top pane (foo).<br />
<br />
{{Note|Numbering for sessions, windows and panes starts at zero, unless you have specified a base-index of 1 in your {{ic|.conf}} }}<br />
<br />
To manage multiple sessions, source separate session files from your conf file:<br />
<br />
# initialize sessions<br />
bind F source-file ~/.tmux/foo<br />
bind B source-file ~/.tmux/bar<br />
<br />
== X clipboard integration ==<br />
<br />
{{Tip|The tmux plugin [https://github.com/tmux-plugins/tmux-yank tmux-yank] provides similar functionality.}}<br />
<br />
It is possible to copy a tmux selection to the X clipboard (and to X primary/secondary selections), and paste from the X clipboard into tmux. The following tmux configuration file snippet integrates the X clipboard/selection with the current tmux selection using the program {{Pkg|xsel}}:<br />
<br />
# Emacs style<br />
bind-key -T copy-mode y send-keys -X copy-pipe-and-cancel "xsel -i -p && xsel -o -p | xsel -i -b"<br />
bind-key C-y run "xsel -o | tmux load-buffer - ; tmux paste-buffer"<br />
<br />
# Vim style<br />
bind-key -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "xsel -i -p && xsel -o -p | xsel -i -b"<br />
bind-key p run "xsel -o | tmux load-buffer - ; tmux paste-buffer"<br />
<br />
Note that it may be necessary to unbind the previous window shortcut with {{ic|unbind p}} for the latter to work.<br />
<br />
{{Pkg|xclip}} could also be used for this purpose. Unlike xsel, it works better when printing a raw bitstream that does not fit the current locale. Nevertheless, it is neater to use xsel because xclip does not close {{ic|STDOUT}} after it has read from the tmux buffer. As such, tmux does not know that the copy task has completed, and continues to wait for xclip to terminate, thereby rendering tmux unresponsive. A workaround is to redirect {{ic|STDOUT}} to {{ic|/dev/null}}:<br />
<br />
# Vim style<br />
bind-key -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "xclip -i -sel clip > /dev/null"<br />
bind-key p run "xclip -o -sel clip | tmux load-buffer - ; tmux paste-buffer"<br />
<br />
=== Urxvt middle click ===<br />
<br />
{{Note|To use this, you need to enable mouse support}}<br />
<br />
There is an unofficial perl extension ([https://github.com/tmux/tmux/wiki/FAQ#how-do-i-copy-a-selection-from-tmux-to-the-systems-clipboard mentioned] in the official [https://github.com/tmux/tmux/wiki/FAQ FAQ]) to enable copying/pasting in and out of urxvt with tmux via Middle Mouse Clicking.<br />
<br />
First, you will need to download the perl script and place it into urxvts perl lib:<br />
<br />
{{bc|wget http://anti.teamidiot.de/static/nei/*/Code/urxvt/osc-xterm-clipboard<br />
mv osc-xterm-clipboard /usr/lib/urxvt/perl/|<br />
}}<br />
<br />
You will also need to enable that perl script in your .Xdefaults:<br />
<br />
{{hc|~/.Xdefaults|<br />
...<br />
*URxvt.perl-ext-common: osc-xterm-clipboard<br />
...<br />
}}<br />
<br />
Next, you want to tell tmux about the new function and enable mouse support (if you have not already):<br />
<br />
{{hc|~/.tmux.conf|<br />
...<br />
set-option -ga terminal-override ',rxvt-uni*:XT:Ms<nowiki>=</nowiki>\E]52;%p1%s;%p2%s\007'<br />
set -g mouse on<br />
...<br />
}}<br />
<br />
That's it. Be sure to end all instances of tmux before trying the new MiddleClick functionality.<br />
<br />
While in tmux, Shift+MiddleMouseClick will paste the clipboard selection while just MiddleMouseClick will paste your tmux buffer.<br />
Outside of tmux, just use MiddleMouseClick to paste your tmux buffer and your standard {{ic|Ctrl+c}} to copy.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Start tmux with default session layout ===<br />
<br />
Session managers like ''tmuxinator'' and [[tmuxp]] make it easy to manage common session configurations.<br />
<br />
For ''tmuxinator'', install {{AUR|tmuxinator}}. Test your installation with<br />
<br />
$ tmuxinator doctor<br />
<br />
==== Get the default layout values ====<br />
<br />
Start tmux as usual and configure your windows and panes layout as you like. When finished, get the current layout values by executing (while you are still within the current tmux session)<br />
<br />
tmux list-windows<br />
<br />
The output may look like this (two windows with 3 panes and 2 panes layout)<br />
<br />
0: default* (3 panes) [274x83] [layout 20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}] @2 (active)<br />
1: remote- (2 panes) [274x83] [layout e3d3,274x83,0,0[274x41,0,0,4,274x41,0,42,7]] @3 <br />
<br />
The Interesting part you need to copy for later use begins after '''[layout...''' and excludes '''... ] @2 (active)'''. For the first window layout you need to copy e.g. '''20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}'''<br />
<br />
==== Define the default tmux layout ====<br />
<br />
Knowing this, you can exit the current tmux session. Following this, you create your default tmux session layout by editing tmuxinator's configuration file (Do not copy the example, get your layout values as described above)<br />
<br />
{{hc|~/.tmuxinator/default.yml|<nowiki><br />
name: default<br />
root: ~/<br />
windows:<br />
- default:<br />
layout: 20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}<br />
panes:<br />
- clear<br />
- vim<br />
- clear && emacs -nw<br />
- remote:<br />
layout: 24ab,274x83,0,0{137x83,0,0,3,136x83,138,0,4}<br />
panes:<br />
- <br />
- <br />
</nowiki>}}<br />
<br />
The example defines two windows named "default" and "remote". With your determined layout values. For each pane you have to use at least one {{ic|-}} line. Within the first window panes you start the commandline "clear" in pane one, "vim" in pane two and "clear && emacs -nw" executes two commands in pane three on each tmux start. The second window layout has two panes without defining any start commmands.<br />
<br />
Test the new default layout with (yes, it is "mux"):<br />
<br />
mux default<br />
<br />
==== Autostart tmux with default tmux layout ====<br />
<br />
If you like to start your terminal session with your default tmux session layout edit<br />
{{hc|~/.bashrc|<nowiki><br />
if [ -z "$TMUX" ]; then<br />
mux default <br />
fi <br />
</nowiki>}}<br />
<br />
==== Alternate approach for default session ====<br />
<br />
Instead of using the above method, one can just write a bash script that when run, will create the default session and attach to it.<br />
Then you can execute it from a terminal to get the pre-designed configuration in that terminal<br />
<br />
#!/bin/bash<br />
tmux new-session -d -n WindowName Command<br />
tmux new-window -n NewWindowName<br />
tmux split-window -v<br />
tmux selectp -t 1<br />
tmux split-window -h<br />
tmux selectw -t 1<br />
tmux -2 attach-session -d<br />
<br />
=== Start tmux in urxvt ===<br />
<br />
Use this command to start urxvt with a started tmux session. I use this with the exec command from my .ratpoisonrc file.<br />
{{bc|<nowiki>urxvt -e bash -c "tmux -q has-session && exec tmux attach-session -d || exec tmux new-session -n$USER -s$USER@$HOSTNAME"</nowiki>}}<br />
<br />
=== Start tmux on every shell login ===<br />
<br />
if [ -x "$(command -v tmux)" ] \<br />
&& [ -n "${DISPLAY}" ] \<br />
&& [ -z "${TMUX}" ] ; then<br />
tmux attach || tmux >/dev/null 2>&1<br />
fi<br />
<br />
What the above snippet does is the following: <br />
<br />
# test if tmux is executable,<br />
# and if a a graphical session is running ('''remove this line if you want tmux to start in any login shell, but it might interfere with [[Xinit#Autostart X at login|autostarting X at login]]'''),<br />
# and if we are not already inside a tmux session,<br />
# then try to attach, if the attachment fails, start a new session.<br />
<br />
If you are using [[#Autostart with systemd|systemd as a user to keep a session alive]], you can replace the last line with the following one to attach to that session and detach all the other connected clients: <br />
<br />
systemctl --user is-active --quiet tmux.service && exec tmux attach-session -d -t "${USER}" || systemctl --user start tmux.service ; exec tmux attach-session -d -t "${USER}" >/dev/null 2>&1<br />
<br />
=== Start a non-login shell ===<br />
<br />
tmux starts a [[login shell]] [https://www.mail-archive.com/tmux-users@lists.sourceforge.net/msg05901.html by default], which may result in multiple negative side effects:<br />
<br />
* Users of [[Wikipedia:fortune (Unix)|fortune]] may notice that quotes are printed when creating a new panel.<br />
* The configuration files for login shells such as {{ic|~/.profile}} are interpreted each time a new panel is created, so commands intended to be run on session initialization (e.g. setting audio level) are executed.<br />
<br />
To disable this behaviour, add to {{ic|~/.tmux.conf}}:<br />
<br />
set -g default-command "${SHELL}"<br />
<br />
=== Use tmux windows like tabs ===<br />
<br />
The following settings added to {{ic|~/.tmux.conf}} allow to use tmux windows like tabs, such as those provided by the reference of these hotkeys — [[Rxvt-unicode/Tips_and_tricks#urxvtq_with_tabbing|urxvt's tabbing extensions]]. An advantage thereof is that these virtual “tabs” are independent of the terminal emulator.<br />
<br />
#urxvt tab like window switching (-n: no prior escape seq)<br />
bind -n S-down new-window<br />
bind -n S-left prev<br />
bind -n S-right next<br />
bind -n C-left swap-window -t -1<br />
bind -n C-right swap-window -t +1<br />
<br />
Of course, those should not overlap with other applications' hotkeys, such as the terminal's. Given that they substitute terminal tabbing that might as well be deactivated, though.<br />
<br />
It can also come handy to supplement the EOT hotkey {{ic|Ctrl+d}} with one for tmux's detach:<br />
<br />
bind-key -n C-j detach<br />
<br />
=== Clients simultaneously interacting with various windows of a session ===<br />
<br />
In [https://mutelight.org/practical-tmux#section-6 Practical Tmux], Brandur Leach writes:<br />
<br />
: Screen and tmux's behaviour for when multiple clients are attached to one session differs slightly. In Screen, each client can be connected to the session but view different windows within it, but in tmux, all clients connected to one session must view the same window.<br />
: This problem can be solved in tmux by spawning two separate sessions and synchronizing the second one to the windows of the first, then pointing a second new session to the first.<br />
<br />
The {{ic|tmx}} script below implements this — the version here is slightly modified to execute {{ic|tmux new-window}} if {{ic|1}} is its second parameter. Invoked as {{ic|tmx ''base_session_name'' [1]}}, it launches the base session if necessary. Otherwise a new "client" session linked to the base, optionally add a new window and attach, setting it to kill itself once it turns "zombie". Don't forget to make it [[executable]].<br />
<br />
{{hc|~/bin/tmx|2=<nowiki><br />
#!/bin/bash<br />
<br />
#<br />
# Modified TMUX start script from:<br />
# http://forums.gentoo.org/viewtopic-t-836006-start-0.html<br />
#<br />
#<br />
<br />
# Works because bash automatically trims by assigning to variables and by <br />
# passing arguments<br />
trim() { echo $1; }<br />
<br />
if [[ -z "$1" ]]; then<br />
echo "Specify session name as the first argument"<br />
exit<br />
fi<br />
<br />
# Only because I often issue `ls` to this script by accident<br />
if [[ "$1" == "ls" ]]; then<br />
tmux ls<br />
exit<br />
fi<br />
<br />
base_session="$1"<br />
# This actually works without the trim() on all systems except OSX<br />
tmux_nb=$(trim `tmux ls | grep "^$base_session" | wc -l`)<br />
if [[ "$tmux_nb" == "0" ]]; then<br />
echo "Launching tmux base session $base_session ..."<br />
tmux new-session -s $base_session<br />
else<br />
# Make sure we are not already in a tmux session<br />
if [[ -z "$TMUX" ]]; then<br />
echo "Launching copy of base session $base_session ..."<br />
# Session id is date and time to prevent conflict<br />
session_id=`date +%Y%m%d%H%M%S`<br />
# Create a new session (without attaching it) and link to base session <br />
# to share windows<br />
tmux new-session -d -t $base_session -s $session_id<br />
if [[ "$2" == "1" ]]; then<br />
# Create a new window in that session<br />
tmux new-window<br />
fi<br />
# Attach to the new session & kill it once orphaned<br />
tmux attach-session -t $session_id \; set-option destroy-unattached<br />
fi<br />
fi<br />
</nowiki>}}<br />
<br />
A useful setting for this is<br />
<br />
setw -g aggressive-resize on<br />
<br />
added to {{ic|~/.tmux.conf}}. It causes tmux to resize a window based on the smallest client actually viewing it, not on the smallest one attached to the entire session.<br />
<br />
An alternative taken from [http://comments.gmane.org/gmane.comp.terminal-emulators.tmux.user/2632]{{Dead link|2021|11|08|status=522}} is to put the following {{ic|~/.bashrc}}:<br />
<br />
{{hc|~/.bashrc|2=<nowiki><br />
function rsc() {<br />
CLIENTID=$1.`date +%S`<br />
tmux new-session -d -t $1 -s $CLIENTID \; set-option destroy-unattached \; attach-session -t $CLIENTID<br />
}<br />
<br />
function mksc() {<br />
tmux new-session -d -s $1<br />
rsc $1<br />
}<br />
</nowiki>}}<br />
<br />
Citing the author:<br />
<br />
: "mksc foo" creates a always detached permanent client named "foo". It also calls "rsc foo" to create a client to newly created session. "rsc foo" creates a new client grouped by "foo" name. It has destroy-unattached turned on so when I leave it, it kills client.<br />
: Therefore, when my computer looses network connectivity, all "foo.something" clients are killed while "foo" remains. I can then call "rsc foo" to continue work from where I stopped.<br />
<br />
=== Correct the TERM variable according to terminal type ===<br />
<br />
Instead of [[#Setting the correct term|setting a fixed TERM variable in tmux]], it is possible to set the proper TERM (either {{ic|screen}} or {{ic|screen-256color}}) according to the type of your terminal emulator:<br />
<br />
{{hc|~/.tmux.conf|<br />
## set the default TERM<br />
set -g default-terminal screen<br />
<br />
## update the TERM variable of terminal emulator when creating a new session or attaching a existing session<br />
set -g update-environment 'DISPLAY SSH_ASKPASS SSH_AGENT_PID SSH_CONNECTION WINDOWID XAUTHORITY TERM'<br />
## determine if we should enable 256-colour support<br />
if "[[ ${TERM} =~ 256color || ${TERM} == fbterm ]]" 'set -g default-terminal screen-256color'<br />
}}<br />
<br />
{{hc|1=~/.zshrc|2=<br />
## workaround for handling TERM variable in multiple tmux sessions properly from https://sourceforge.net/p/tmux/mailman/message/32751663/{{Dead link|2020|04|03|status=404}} by Nicholas Marriott<br />
if [[ -n ${TMUX} && -n ${commands[tmux]} ]];then<br />
case $(tmux showenv TERM 2>/dev/null) in<br />
*256color) ;&<br />
TERM=fbterm)<br />
TERM=screen-256color ;;<br />
*)<br />
TERM=screen<br />
esac<br />
fi<br />
}}<br />
<br />
=== Reload an updated configuration without restarting tmux ===<br />
<br />
By default tmux reads {{ic|~/.tmux.conf}} only if it was not already running. To have tmux load a configuration file afterwards, execute:<br />
<br />
tmux source-file <path><br />
<br />
This can be added to {{ic|~/.tmux.conf}} as e. g.:<br />
<br />
bind r source-file <path><br />
<br />
You can also do ^: and type :<br />
source .tmux.conf<br />
<br />
=== Template script to run program in new session or attach to existing one ===<br />
<br />
This script checks for a program presumed to have been started by a previous run of itself. Unless found it creates a new tmux session and attaches to a window named after and running the program. If however the program was found it merely attaches to the session and selects the window.<br />
<br />
#!/bin/bash<br />
<br />
PID=$(pidof $1)<br />
<br />
if [ -z "$PID" ]; then<br />
tmux new-session -d -s main ;<br />
tmux new-window -t main -n $1 "$*" ;<br />
fi<br />
tmux attach-session -d -t main ;<br />
tmux select-window -t $1 ;<br />
exit 0<br />
<br />
A derived version to run ''irssi'' with the ''nicklist'' plugin can be found on [[Irssi#Irssi with nicklist in tmux|its ArchWiki page]].<br />
<br />
=== Terminal emulator window titles ===<br />
<br />
If you SSH into a host in a tmux window, you will notice the window title of your terminal emulator remains to be {{ic|user@localhost}} rather than {{ic|user@server}}. To allow the title bar to adapt to whatever host you connect to, set the following in {{ic|~/.tmux.conf}}<br />
<br />
set -g set-titles on<br />
set -g set-titles-string "#T"<br />
<br />
For {{ic|set-titles-string}}, {{ic|#T}} will display {{ic|user@host:~}} and change accordingly as you connect to different hosts.<br />
<br />
=== Automatic layouting ===<br />
<br />
When creating new splits or destroying older ones the currently selected layout is not applied. To fix that, add following binds which will apply the currently selected layout to new or remaining panes:<br />
<br />
bind-key -n M-c kill-pane \; select-layout<br />
bind-key -n M-n split-window \; select-layout<br />
<br />
{{Tip|You may be interested in {{AUR|tmux-xpanes}} which makes managing window layouts and SSH connections easy.}}<br />
<br />
=== Vim colorscheme not loading ===<br />
<br />
See the following if your vim colorscheme is not loading in tmux: [https://stackoverflow.com/a/47994805] [https://github.com/vim/vim/issues/993#issuecomment-255651605]<br />
<br />
=== Vim friendly configuration ===<br />
<br />
See [https://gist.github.com/Lartza/6a7a62466a8a3e436234412d9b1c5066] for a configuration friendly to [[vim]] users.<br />
<br />
=== Friendly pane splitting ===<br />
<br />
The default key-binding for splitting a pane vertically is {{ic|Ctrl+b %}} and for splitting a pane horizontally is {{ic|Ctrl+b "}}. That can be difficult to type depending of your keyboard layout and it is also hard to remember.<br />
<br />
A more friendly key-binding is to use {{ic|Ctrl+b h}} for splitting horizontally and {{ic|Ctrl+b v}} for splitting a pane vertically, it is also very convenient to remember.<br />
<br />
To make this change, add these lines in {{ic|~/.tmux.conf}}:<br />
<br />
{{bc|<br />
# More friendly split pane<br />
bind-key h split-window -h<br />
bind-key v split-window -v<br />
}}<br />
<br />
=== Inhibit system suspension ===<br />
<br />
If tmux hangs when connected from another device because the host goes to sleep, run session's shell command with an inhibition lock:<br />
<br />
tmux new-session -A "systemd-inhibit --what=idle $SHELL"<br />
<br />
== Troubleshooting ==<br />
<br />
=== Scrolling issues ===<br />
<br />
If you have issues scrolling with Shift-Page Up/Down in your terminal, the following will remove the smcup and rmcup capabilities for any term that reports itself as anything beginning with {{ic|xterm}}:<br />
<br />
set -ga terminal-overrides ',xterm*:smcup@:rmcup@'<br />
<br />
This tricks the terminal emulator into thinking tmux is a full screen application like pico or mutt[https://superuser.com/questions/310251/use-terminal-scrollbar-with-tmux], which will make the scrollback be recorded properly. Beware however, it will get a bit messed up when switching between windows/panes. Consider using tmux's native scrollback instead.<br />
<br />
=== Mouse scrolling ===<br />
<br />
{{Note|This interferes with selection buffer copying and pasting. To copy/paste to/from the selection buffer hold the shift key.}}<br />
<br />
If you want to scroll with your mouse wheel, ensure mode-mouse is on in .tmux.conf<br />
set -g mouse on<br />
<br />
You can set scroll History with:<br />
set -g history-limit 30000<br />
<br />
For mouse wheel scrolling as from tmux 2.1 try adding one or both of these to ~/.tmux.conf<br />
bind -T root WheelUpPane if-shell -F -t = "#{alternate_on}" "send-keys -M" "select-pane -t =; copy-mode -e; send-keys -M"<br />
bind -T root WheelDownPane if-shell -F -t = "#{alternate_on}" "send-keys -M" "select-pane -t =; send-keys -M"<br />
<br />
Though the above will only scroll one line at a time, add this solution to scroll an entire page instead<br />
bind -t vi-copy WheelUpPane page-up<br />
bind -t vi-copy WheelDownPane page-down<br />
bind -t emacs-copy WheelUpPane page-up<br />
bind -t emacs-copy WheelDownPane page-down<br />
<br />
=== Terminal emulator does not support UTF-8 mouse events ===<br />
<br />
When the terminal emulator does not support the UTF-8 mouse events and the {{ic|mouse on}} tmux option is set, left-clicking inside the terminal window might paste strings like {{ic|[M#}} or {{ic|[Ma}} into the promt.<br />
<br />
To solve this issue set:<br />
<br />
set -g mouse-utf8 off<br />
<br />
=== Shift+F6 not working in Midnight Commander ===<br />
<br />
See [[Midnight Commander#Broken shortcuts]].<br />
<br />
== See also ==<br />
<br />
* [https://bbs.archlinux.org/viewtopic.php?id=84157&p=1 BBS topic]<br />
* [http://www.dayid.org/os/notes/tm.html Screen and tmux feature comparison]<br />
* [https://github.com/Lokaltog/powerline powerline], a dynamic statusbar for tmux<br />
* [https://github.com/tmux-plugins Plugins for tmux]<br />
* [https://github.com/gpakosz/.tmux Oh My Tmux!]<br />
<br />
'''Tutorials'''<br />
<br />
* [https://mutelight.org/practical-tmux Practical Tmux]<br />
* manual page {{man|1|tmux}}<br />
* [https://blog.hawkhost.com/2010/06/28/tmux-the-terminal-multiplexer/ Tmux tutorial Part 1] and [https://blog.hawkhost.com/2010/07/02/tmux-%E2%80%93-the-terminal-multiplexer-part-2 Part 2]<br />
* [https://leanpub.com/the-tao-of-tmux/read ''The Tao of tmux''], an ebook by Tony Narlock, author of [https://tmuxp.git-pull.com tmuxp] and [https://libtmux.git-pull.com libtmux]</div>Fethbitahttps://wiki.archlinux.org/index.php?title=Tmux&diff=731277Tmux2022-06-01T13:57:38Z<p>Fethbita: Edit the comment for snippet to reflect the code better</p>
<hr />
<div>{{Lowercase title}}<br />
[[Category:Terminal multiplexers]]<br />
[[de:Tmux]]<br />
[[ja:Tmux]]<br />
[[zh-hans:Tmux]]<br />
[https://tmux.github.io/ tmux] is a "terminal multiplexer: it enables a number of terminals (or windows), each running a separate program, to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached." <br />
<br />
tmux is an ISC-licensed alternative to [[GNU Screen]]. Although similar, there are many differences between the programs, as noted on the [https://github.com/tmux/tmux/wiki/FAQ tmux FAQ page].<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|tmux}} package.<br />
Optionally, install {{AUR|tmux-bash-completion-git}} to provide bash completion functions for tmux.<br />
<br />
== Configuration ==<br />
<br />
By default, tmux looks for user-specific configuration at {{ic|~/.tmux.conf}}, though {{ic|~/.config/tmux/tmux.conf}} (hardcoded, {{ic|$XDG_CONFIG_HOME}} is ignored) works too. A global configuration file may be provided at {{ic|/etc/tmux.conf}} though by default Arch does not ship such a file.<br />
<br />
=== Key bindings ===<br />
<br />
By default, command key bindings are prefixed by {{ic|Ctrl+b}}. For example, to vertically split a window type {{ic|Ctrl+b %}}.<br />
<br />
After splitting a window into multiple panes, a pane can be resized by the hitting prefix key (e.g. {{ic|Ctrl+b}}) and, while continuing to hold {{ic|Ctrl}}, press Left/Right/Up/Down. Swapping panes is achieved in the same manner, but by hitting ''o'' instead of a directional key.<br />
<br />
Key bindings may be changed with the bind and unbind commands in {{ic|tmux.conf}}. For example, the default prefix binding of {{ic|Ctrl+b}} can be changed to {{ic|Ctrl+a}} by adding the following commands in your configuration file:<br />
<br />
{{bc|<br />
unbind C-b<br />
set -g prefix C-a<br />
bind C-a send-prefix<br />
}}<br />
<br />
{{Tip|Quote special characters to use them as prefix. You may also use {{ic|Alt}} (called Meta) instead of {{ic|Ctrl}}. For example: {{ic|set -g prefix m-'\'}}}}<br />
<br />
To create a new window you can use {{ic|Ctrl+b c}} and move forward one window with {{ic|Ctrl+b n}} and backwards one window with {{ic|Ctrl+b p}}.<br />
<br />
Additional ways to move between windows include the following:<br />
<br />
Ctrl+b l (Move to the previously selected window)<br />
Ctrl+b w (List all windows / window numbers)<br />
Ctrl+b <window number> (Move to the specified window number, the default bindings are from 0 – 9)<br />
Ctrl+b q (Show pane numbers, when the numbers show up type the key to goto that pane)<br />
<br />
tmux has a find-window option & key binding to ease navigation of many windows:<br />
<br />
Ctrl+b f <window name> (Search for window name)<br />
Ctrl+b w (Select from interactive list of windows)<br />
<br />
==== Copy Mode ====<br />
<br />
A tmux window may be in one of several modes. The default permits direct access to the terminal attached to the window; the other is copy mode. Once in copy mode you can navigate the buffer including scrolling the history. Use [[vi]] or [[emacs]]-style key bindings in copy mode. The default is emacs, unless VISUAL or EDITOR contains ‘vi’<br />
<br />
To enter copy mode do the following:<br />
<br />
Ctrl+b [<br />
<br />
You can navigate the buffer as you would in your default editor.<br />
<br />
To quit copy mode, use one of the following keybindings:<br />
<br />
vi mode:<br />
q<br />
emacs mode:<br />
Esc<br />
<br />
=== Browsing URLs ===<br />
<br />
To browse URLs inside tmux you must have {{AUR|urlview}} installed and configured.<br />
<br />
Inside a new terminal:<br />
bind-key u capture-pane \; save-buffer /tmp/tmux-buffer \; run-shell "$TERMINAL -e urlview /tmp/tmux-buffer"<br />
<br />
Or inside a new tmux window (no new terminal needed):<br />
bind-key u capture-pane \; save-buffer /tmp/tmux-buffer \; new-window -n "urlview" '$SHELL -c "urlview < /tmp/tmux-buffer"'<br />
<br />
=== Setting the correct term ===<br />
<br />
==== 256 colors ====<br />
<br />
If you are using a 256 colour terminal, you will need to set the correct term in tmux. As of [https://raw.githubusercontent.com/tmux/tmux/master/CHANGES tmux 2.1], this is now ''tmux'', or ''tmux-256color''. You can do this in {{ic|tmux.conf}}:<br />
<br />
set -g default-terminal "tmux-256color" <br />
<br />
Other, older alternatives, include ''screen'', or ''screen-256color'':<br />
<br />
set -g default-terminal "screen-256color"<br />
<br />
Also, if tmux messes up, you can force tmux to assume that the terminal support 256 colors, by adding this in your .bashrc:<br />
<br />
alias tmux="tmux -2"<br />
<br />
==== 24-bit color ====<br />
<br />
tmux supports 24-bit color as of version 2.2 [https://github.com/tmux/tmux/commit/427b8204268af5548d09b830e101c59daa095df9]. If your terminal supports 24-bit color (see this [https://gist.github.com/XVilka/8346728 gist]), add your terminal to the {{ic|terminal-overrides}} setting. For example, if you use [[Termite]], you would add:<br />
<br />
set -ga terminal-overrides ",xterm-termite:Tc"<br />
<br />
For other terminals, replace {{ic|xterm-termite}} with the relevant terminal type (stored in {{ic|$TERM}}). See the {{man|1|tmux}} man page for details about the {{ic|Tc}} terminfo extension.<br />
<br />
==== xterm-keys ====<br />
<br />
To enable xterm-keys in your {{ic|tmux.conf}}, you have to add the following line<br />
<br />
set-option -g xterm-keys on<br />
<br />
If you enable xterm-keys in your {{ic|tmux.conf}}, then you need to build a custom terminfo to declare the new escape codes or applications will not know about them. Compile the following with {{ic|tic}} and you can use "xterm-screen-256color" as your TERM:<br />
<br />
# A screen- based TERMINFO that declares the escape sequences<br />
# enabled by the tmux config "set-window-option -g xterm-keys".<br />
#<br />
# Prefix the name with xterm- since some applications inspect<br />
# the TERM *name* in addition to the terminal capabilities advertised.<br />
xterm-screen-256color|GNU Screen with 256 colors bce and tmux xterm-keys,<br />
<br />
# As of Nov'11, the below keys are picked up by<br />
# .../tmux/blob/master/trunk/xterm-keys.c:<br />
kDC=\E[3;2~, kEND=\E[1;2F, kHOM=\E[1;2H,<br />
kIC=\E[2;2~, kLFT=\E[1;2D, kNXT=\E[6;2~, kPRV=\E[5;2~,<br />
kRIT=\E[1;2C,<br />
<br />
# Change this to screen-256color if the terminal you run tmux in<br />
# doesn't support bce:<br />
use=screen-256color-bce,<br />
<br />
To check if your terminal support bce, you can use {{ic|tic -c}}:<br />
<br />
$ tic -c xterm-screen-256color <br />
"xterm-screen-256color", line 16, terminal 'xterm-screen-256color': resolution of use=screen-256color-bce failed<br />
<br />
To compile with tic:<br />
<br />
$ tic xterm-screen-256color <br />
<br />
The file will be compiled and saved in $HOME/.terminfo or in /usr/share/terminfo/ if run as root (and so available system-wide).<br />
<br />
=== Other Settings ===<br />
<br />
To limit the scrollback buffer to 10000 lines:<br />
set -g history-limit 10000<br />
<br />
Mouse can be toggled with<br />
bind-key m set-option -g mouse \; display "Mouse: #{?mouse,ON,OFF}"<br />
<br />
=== Autostart with systemd ===<br />
<br />
There are some notable advantages to starting a tmux server at startup.<br />
Notably, when you start a new tmux session, having the service already running reduces any delays in the startup.<br />
<br />
Furthermore, any customization attached to your tmux session will be retained and your tmux session can be made to persist even if you have never logged in, if you have some reason to do that (like a heavily scripted tmux configuration or shared user tmux sessions).<br />
<br />
The service below starts ''tmux'' for the specified user (i.e. start with {{ic|tmux@''username''.service}}):<br />
<br />
{{hc|/etc/systemd/system/tmux@.service|<nowiki><br />
[Unit]<br />
Description=Start tmux in detached session<br />
<br />
[Service]<br />
Type=forking<br />
User=%I<br />
ExecStart=/usr/bin/tmux new-session -s %u -d<br />
ExecStop=/usr/bin/tmux kill-session -t %u<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
{{Tip|You may want to add {{ic|1=WorkingDirectory=''custom_path''}} to customize working directory. If set to {{ic|~}}, the home directory of the user specified in {{ic|1=User=}} is used.}}<br />
<br />
Alternatively, you can place this file within your [[systemd/User]] directory (without {{ic|1=User=%I}} and by replacing {{ic|multi-user.target}} with {{ic|default.target}} in {{ic|WantedBy}}), for example {{ic|~/.config/systemd/user/tmux.service}}. This way the tmux service will start when you log in, unless you also enable [[systemd/User#Automatic start-up of systemd user instances]].<br />
<br />
== Session initialization ==<br />
<br />
You can have tmux open a session with preloaded windows by including those details in your {{ic|~/.tmux.conf}}:<br />
<br />
new -n WindowName Command<br />
neww -n WindowName Command<br />
neww -n WindowName Command<br />
<br />
To start a session with split windows (multiple panes), include the splitw command below the neww you would like to split; thus:<br />
<br />
new -s SessionName -n WindowName Command<br />
neww -n foo/bar foo<br />
splitw -v -p 50 -t 0 bar<br />
selectw -t 1 <br />
selectp -t 0<br />
<br />
would open 2 windows, the second of which would be named foo/bar and would be split vertically in half (50%) with foo running above bar. Focus would be in window 2 (foo/bar), top pane (foo).<br />
<br />
{{Note|Numbering for sessions, windows and panes starts at zero, unless you have specified a base-index of 1 in your {{ic|.conf}} }}<br />
<br />
To manage multiple sessions, source separate session files from your conf file:<br />
<br />
# initialize sessions<br />
bind F source-file ~/.tmux/foo<br />
bind B source-file ~/.tmux/bar<br />
<br />
== X clipboard integration ==<br />
<br />
{{Tip|The tmux plugin [https://github.com/tmux-plugins/tmux-yank tmux-yank] provides similar functionality.}}<br />
<br />
It is possible to copy a tmux selection to the X clipboard (and to X primary/secondary selections), and paste from the X clipboard into tmux. The following tmux configuration file snippet integrates the X clipboard/selection with the current tmux selection using the program {{Pkg|xsel}}:<br />
<br />
# Emacs style<br />
bind-key -T copy-mode y send-keys -X copy-pipe-and-cancel "xsel -i -p && xsel -o -p | xsel -i -b"<br />
bind-key C-y run "xsel -o | tmux load-buffer - ; tmux paste-buffer"<br />
<br />
# Vim style<br />
bind-key -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "xsel -i -p && xsel -o -p | xsel -i -b"<br />
bind-key p run "xsel -o | tmux load-buffer - ; tmux paste-buffer"<br />
<br />
Note that it may be necessary to unbind the previous window shortcut with {{ic|unbind p}} for the latter to work.<br />
<br />
{{Pkg|xclip}} could also be used for this purpose. Unlike xsel, it works better when printing a raw bitstream that does not fit the current locale. Nevertheless, it is neater to use xsel because xclip does not close {{ic|STDOUT}} after it has read from the tmux buffer. As such, tmux does not know that the copy task has completed, and continues to wait for xclip to terminate, thereby rendering tmux unresponsive. A workaround is to redirect {{ic|STDOUT}} to {{ic|/dev/null}}:<br />
<br />
# Vim style<br />
bind-key -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "xclip -i -sel clip > /dev/null"<br />
bind-key p run "xclip -o -sel clip | tmux load-buffer - ; tmux paste-buffer"<br />
<br />
=== Urxvt middle click ===<br />
<br />
{{Note|To use this, you need to enable mouse support}}<br />
<br />
There is an unofficial perl extension ([https://github.com/tmux/tmux/wiki/FAQ#how-do-i-copy-a-selection-from-tmux-to-the-systems-clipboard mentioned] in the official [https://github.com/tmux/tmux/wiki/FAQ FAQ]) to enable copying/pasting in and out of urxvt with tmux via Middle Mouse Clicking.<br />
<br />
First, you will need to download the perl script and place it into urxvts perl lib:<br />
<br />
{{bc|wget http://anti.teamidiot.de/static/nei/*/Code/urxvt/osc-xterm-clipboard<br />
mv osc-xterm-clipboard /usr/lib/urxvt/perl/|<br />
}}<br />
<br />
You will also need to enable that perl script in your .Xdefaults:<br />
<br />
{{hc|~/.Xdefaults|<br />
...<br />
*URxvt.perl-ext-common: osc-xterm-clipboard<br />
...<br />
}}<br />
<br />
Next, you want to tell tmux about the new function and enable mouse support (if you have not already):<br />
<br />
{{hc|~/.tmux.conf|<br />
...<br />
set-option -ga terminal-override ',rxvt-uni*:XT:Ms<nowiki>=</nowiki>\E]52;%p1%s;%p2%s\007'<br />
set -g mouse on<br />
...<br />
}}<br />
<br />
That's it. Be sure to end all instances of tmux before trying the new MiddleClick functionality.<br />
<br />
While in tmux, Shift+MiddleMouseClick will paste the clipboard selection while just MiddleMouseClick will paste your tmux buffer.<br />
Outside of tmux, just use MiddleMouseClick to paste your tmux buffer and your standard {{ic|Ctrl+c}} to copy.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Start tmux with default session layout ===<br />
<br />
Session managers like ''tmuxinator'' and [[tmuxp]] make it easy to manage common session configurations.<br />
<br />
For ''tmuxinator'', install {{AUR|tmuxinator}}. Test your installation with<br />
<br />
$ tmuxinator doctor<br />
<br />
==== Get the default layout values ====<br />
<br />
Start tmux as usual and configure your windows and panes layout as you like. When finished, get the current layout values by executing (while you are still within the current tmux session)<br />
<br />
tmux list-windows<br />
<br />
The output may look like this (two windows with 3 panes and 2 panes layout)<br />
<br />
0: default* (3 panes) [274x83] [layout 20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}] @2 (active)<br />
1: remote- (2 panes) [274x83] [layout e3d3,274x83,0,0[274x41,0,0,4,274x41,0,42,7]] @3 <br />
<br />
The Interesting part you need to copy for later use begins after '''[layout...''' and excludes '''... ] @2 (active)'''. For the first window layout you need to copy e.g. '''20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}'''<br />
<br />
==== Define the default tmux layout ====<br />
<br />
Knowing this, you can exit the current tmux session. Following this, you create your default tmux session layout by editing tmuxinator's configuration file (Do not copy the example, get your layout values as described above)<br />
<br />
{{hc|~/.tmuxinator/default.yml|<nowiki><br />
name: default<br />
root: ~/<br />
windows:<br />
- default:<br />
layout: 20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}<br />
panes:<br />
- clear<br />
- vim<br />
- clear && emacs -nw<br />
- remote:<br />
layout: 24ab,274x83,0,0{137x83,0,0,3,136x83,138,0,4}<br />
panes:<br />
- <br />
- <br />
</nowiki>}}<br />
<br />
The example defines two windows named "default" and "remote". With your determined layout values. For each pane you have to use at least one {{ic|-}} line. Within the first window panes you start the commandline "clear" in pane one, "vim" in pane two and "clear && emacs -nw" executes two commands in pane three on each tmux start. The second window layout has two panes without defining any start commmands.<br />
<br />
Test the new default layout with (yes, it is "mux"):<br />
<br />
mux default<br />
<br />
==== Autostart tmux with default tmux layout ====<br />
<br />
If you like to start your terminal session with your default tmux session layout edit<br />
{{hc|~/.bashrc|<nowiki><br />
if [ -z "$TMUX" ]; then<br />
mux default <br />
fi <br />
</nowiki>}}<br />
<br />
==== Alternate approach for default session ====<br />
<br />
Instead of using the above method, one can just write a bash script that when run, will create the default session and attach to it.<br />
Then you can execute it from a terminal to get the pre-designed configuration in that terminal<br />
<br />
#!/bin/bash<br />
tmux new-session -d -n WindowName Command<br />
tmux new-window -n NewWindowName<br />
tmux split-window -v<br />
tmux selectp -t 1<br />
tmux split-window -h<br />
tmux selectw -t 1<br />
tmux -2 attach-session -d<br />
<br />
=== Start tmux in urxvt ===<br />
<br />
Use this command to start urxvt with a started tmux session. I use this with the exec command from my .ratpoisonrc file.<br />
{{bc|<nowiki>urxvt -e bash -c "tmux -q has-session && exec tmux attach-session -d || exec tmux new-session -n$USER -s$USER@$HOSTNAME"</nowiki>}}<br />
<br />
=== Start tmux on every shell login ===<br />
<br />
The following snippet starts a session if one is not already present. Otherwise, tmux attaches to the preexisting session. <br />
{{bc|<nowiki><br />
# if tmux is executable and not inside a tmux session, then try to attach.<br />
# if attachment fails, start a new session<br />
[ -x "$(command -v tmux)" ] \<br />
&& [ -z "${TMUX}" ] \<br />
&& { tmux attach || tmux; } >/dev/null 2>&1<br />
</nowiki>}}<br />
<br />
Note that the above snippet causes tmux to launch in ''any'' login shell, including the virtual console. This interferes with [[Xinit#Autostart X at login]]. <br />
<br />
To launch tmux only when there is a graphical environment running, use this instead:<br />
<br />
{{bc|<nowiki><br />
# if tmux is executable, X is running, and not inside a tmux session, then try to attach.<br />
# if attachment fails, start a new session<br />
if [ -x "$(command -v tmux)" ] && [ -n "${DISPLAY}" ]; then<br />
[ -z "${TMUX}" ] && { tmux attach || tmux; } >/dev/null 2>&1<br />
fi<br />
</nowiki>}}<br />
<br />
If you are using [[#Autostart with systemd|systemd as a user to keep a session alive]], you can use the following snippet to attach to that session and detach all the other connected clients:<br />
<br />
{{bc|<nowiki><br />
# if tmux is executable and not inside a tmux session, and systemctl service is running try to attach.<br />
# if attachment fails, start the systemctl service and attach<br />
[ -x "$(command -v tmux)" ] \<br />
&& [ -z "${TMUX}" ] \<br />
&& { systemctl --user is-active --quiet tmux.service && exec tmux attach-session -d -t "${USER}" || systemctl --user start tmux.service ; exec tmux attach-session -d -t "${USER}"; } >/dev/null 2>&1<br />
</nowiki>}}<br />
<br />
=== Start a non-login shell ===<br />
<br />
tmux starts a [[login shell]] [https://www.mail-archive.com/tmux-users@lists.sourceforge.net/msg05901.html by default], which may result in multiple negative side effects:<br />
<br />
* Users of [[Wikipedia:fortune (Unix)|fortune]] may notice that quotes are printed when creating a new panel.<br />
* The configuration files for login shells such as {{ic|~/.profile}} are interpreted each time a new panel is created, so commands intended to be run on session initialization (e.g. setting audio level) are executed.<br />
<br />
To disable this behaviour, add to {{ic|~/.tmux.conf}}:<br />
<br />
set -g default-command "${SHELL}"<br />
<br />
=== Use tmux windows like tabs ===<br />
<br />
The following settings added to {{ic|~/.tmux.conf}} allow to use tmux windows like tabs, such as those provided by the reference of these hotkeys — [[Rxvt-unicode/Tips_and_tricks#urxvtq_with_tabbing|urxvt's tabbing extensions]]. An advantage thereof is that these virtual “tabs” are independent of the terminal emulator.<br />
<br />
#urxvt tab like window switching (-n: no prior escape seq)<br />
bind -n S-down new-window<br />
bind -n S-left prev<br />
bind -n S-right next<br />
bind -n C-left swap-window -t -1<br />
bind -n C-right swap-window -t +1<br />
<br />
Of course, those should not overlap with other applications' hotkeys, such as the terminal's. Given that they substitute terminal tabbing that might as well be deactivated, though.<br />
<br />
It can also come handy to supplement the EOT hotkey {{ic|Ctrl+d}} with one for tmux's detach:<br />
<br />
bind-key -n C-j detach<br />
<br />
=== Clients simultaneously interacting with various windows of a session ===<br />
<br />
In [https://mutelight.org/practical-tmux#section-6 Practical Tmux], Brandur Leach writes:<br />
<br />
: Screen and tmux's behaviour for when multiple clients are attached to one session differs slightly. In Screen, each client can be connected to the session but view different windows within it, but in tmux, all clients connected to one session must view the same window.<br />
: This problem can be solved in tmux by spawning two separate sessions and synchronizing the second one to the windows of the first, then pointing a second new session to the first.<br />
<br />
The {{ic|tmx}} script below implements this — the version here is slightly modified to execute {{ic|tmux new-window}} if {{ic|1}} is its second parameter. Invoked as {{ic|tmx ''base_session_name'' [1]}}, it launches the base session if necessary. Otherwise a new "client" session linked to the base, optionally add a new window and attach, setting it to kill itself once it turns "zombie". Don't forget to make it [[executable]].<br />
<br />
{{hc|~/bin/tmx|2=<nowiki><br />
#!/bin/bash<br />
<br />
#<br />
# Modified TMUX start script from:<br />
# http://forums.gentoo.org/viewtopic-t-836006-start-0.html<br />
#<br />
#<br />
<br />
# Works because bash automatically trims by assigning to variables and by <br />
# passing arguments<br />
trim() { echo $1; }<br />
<br />
if [[ -z "$1" ]]; then<br />
echo "Specify session name as the first argument"<br />
exit<br />
fi<br />
<br />
# Only because I often issue `ls` to this script by accident<br />
if [[ "$1" == "ls" ]]; then<br />
tmux ls<br />
exit<br />
fi<br />
<br />
base_session="$1"<br />
# This actually works without the trim() on all systems except OSX<br />
tmux_nb=$(trim `tmux ls | grep "^$base_session" | wc -l`)<br />
if [[ "$tmux_nb" == "0" ]]; then<br />
echo "Launching tmux base session $base_session ..."<br />
tmux new-session -s $base_session<br />
else<br />
# Make sure we are not already in a tmux session<br />
if [[ -z "$TMUX" ]]; then<br />
echo "Launching copy of base session $base_session ..."<br />
# Session id is date and time to prevent conflict<br />
session_id=`date +%Y%m%d%H%M%S`<br />
# Create a new session (without attaching it) and link to base session <br />
# to share windows<br />
tmux new-session -d -t $base_session -s $session_id<br />
if [[ "$2" == "1" ]]; then<br />
# Create a new window in that session<br />
tmux new-window<br />
fi<br />
# Attach to the new session & kill it once orphaned<br />
tmux attach-session -t $session_id \; set-option destroy-unattached<br />
fi<br />
fi<br />
</nowiki>}}<br />
<br />
A useful setting for this is<br />
<br />
setw -g aggressive-resize on<br />
<br />
added to {{ic|~/.tmux.conf}}. It causes tmux to resize a window based on the smallest client actually viewing it, not on the smallest one attached to the entire session.<br />
<br />
An alternative taken from [http://comments.gmane.org/gmane.comp.terminal-emulators.tmux.user/2632]{{Dead link|2021|11|08|status=522}} is to put the following {{ic|~/.bashrc}}:<br />
<br />
{{hc|~/.bashrc|2=<nowiki><br />
function rsc() {<br />
CLIENTID=$1.`date +%S`<br />
tmux new-session -d -t $1 -s $CLIENTID \; set-option destroy-unattached \; attach-session -t $CLIENTID<br />
}<br />
<br />
function mksc() {<br />
tmux new-session -d -s $1<br />
rsc $1<br />
}<br />
</nowiki>}}<br />
<br />
Citing the author:<br />
<br />
: "mksc foo" creates a always detached permanent client named "foo". It also calls "rsc foo" to create a client to newly created session. "rsc foo" creates a new client grouped by "foo" name. It has destroy-unattached turned on so when I leave it, it kills client.<br />
: Therefore, when my computer looses network connectivity, all "foo.something" clients are killed while "foo" remains. I can then call "rsc foo" to continue work from where I stopped.<br />
<br />
=== Correct the TERM variable according to terminal type ===<br />
<br />
Instead of [[#Setting the correct term|setting a fixed TERM variable in tmux]], it is possible to set the proper TERM (either {{ic|screen}} or {{ic|screen-256color}}) according to the type of your terminal emulator:<br />
<br />
{{hc|~/.tmux.conf|<br />
## set the default TERM<br />
set -g default-terminal screen<br />
<br />
## update the TERM variable of terminal emulator when creating a new session or attaching a existing session<br />
set -g update-environment 'DISPLAY SSH_ASKPASS SSH_AGENT_PID SSH_CONNECTION WINDOWID XAUTHORITY TERM'<br />
## determine if we should enable 256-colour support<br />
if "[[ ${TERM} =~ 256color || ${TERM} == fbterm ]]" 'set -g default-terminal screen-256color'<br />
}}<br />
<br />
{{hc|1=~/.zshrc|2=<br />
## workaround for handling TERM variable in multiple tmux sessions properly from https://sourceforge.net/p/tmux/mailman/message/32751663/{{Dead link|2020|04|03|status=404}} by Nicholas Marriott<br />
if [[ -n ${TMUX} && -n ${commands[tmux]} ]];then<br />
case $(tmux showenv TERM 2>/dev/null) in<br />
*256color) ;&<br />
TERM=fbterm)<br />
TERM=screen-256color ;;<br />
*)<br />
TERM=screen<br />
esac<br />
fi<br />
}}<br />
<br />
=== Reload an updated configuration without restarting tmux ===<br />
<br />
By default tmux reads {{ic|~/.tmux.conf}} only if it was not already running. To have tmux load a configuration file afterwards, execute:<br />
<br />
tmux source-file <path><br />
<br />
This can be added to {{ic|~/.tmux.conf}} as e. g.:<br />
<br />
bind r source-file <path><br />
<br />
You can also do ^: and type :<br />
source .tmux.conf<br />
<br />
=== Template script to run program in new session or attach to existing one ===<br />
<br />
This script checks for a program presumed to have been started by a previous run of itself. Unless found it creates a new tmux session and attaches to a window named after and running the program. If however the program was found it merely attaches to the session and selects the window.<br />
<br />
#!/bin/bash<br />
<br />
PID=$(pidof $1)<br />
<br />
if [ -z "$PID" ]; then<br />
tmux new-session -d -s main ;<br />
tmux new-window -t main -n $1 "$*" ;<br />
fi<br />
tmux attach-session -d -t main ;<br />
tmux select-window -t $1 ;<br />
exit 0<br />
<br />
A derived version to run ''irssi'' with the ''nicklist'' plugin can be found on [[Irssi#Irssi with nicklist in tmux|its ArchWiki page]].<br />
<br />
=== Terminal emulator window titles ===<br />
<br />
If you SSH into a host in a tmux window, you will notice the window title of your terminal emulator remains to be {{ic|user@localhost}} rather than {{ic|user@server}}. To allow the title bar to adapt to whatever host you connect to, set the following in {{ic|~/.tmux.conf}}<br />
<br />
set -g set-titles on<br />
set -g set-titles-string "#T"<br />
<br />
For {{ic|set-titles-string}}, {{ic|#T}} will display {{ic|user@host:~}} and change accordingly as you connect to different hosts.<br />
<br />
=== Automatic layouting ===<br />
<br />
When creating new splits or destroying older ones the currently selected layout is not applied. To fix that, add following binds which will apply the currently selected layout to new or remaining panes:<br />
<br />
bind-key -n M-c kill-pane \; select-layout<br />
bind-key -n M-n split-window \; select-layout<br />
<br />
{{Tip|You may be interested in {{AUR|tmux-xpanes}} which makes managing window layouts and SSH connections easy.}}<br />
<br />
=== Vim colorscheme not loading ===<br />
<br />
See the following if your vim colorscheme is not loading in tmux: [https://stackoverflow.com/a/47994805] [https://github.com/vim/vim/issues/993#issuecomment-255651605]<br />
<br />
=== Vim friendly configuration ===<br />
<br />
See [https://gist.github.com/Lartza/6a7a62466a8a3e436234412d9b1c5066] for a configuration friendly to [[vim]] users.<br />
<br />
=== Friendly pane splitting ===<br />
<br />
The default key-binding for splitting a pane vertically is {{ic|Ctrl+b %}} and for splitting a pane horizontally is {{ic|Ctrl+b "}}. That can be difficult to type depending of your keyboard layout and it is also hard to remember.<br />
<br />
A more friendly key-binding is to use {{ic|Ctrl+b h}} for splitting horizontally and {{ic|Ctrl+b v}} for splitting a pane vertically, it is also very convenient to remember.<br />
<br />
To make this change, add these lines in {{ic|~/.tmux.conf}}:<br />
<br />
{{bc|<br />
# More friendly split pane<br />
bind-key h split-window -h<br />
bind-key v split-window -v<br />
}}<br />
<br />
=== Inhibit system suspension ===<br />
<br />
If tmux hangs when connected from another device because the host goes to sleep, run session's shell command with an inhibition lock:<br />
<br />
tmux new-session -A "systemd-inhibit --what=idle $SHELL"<br />
<br />
== Troubleshooting ==<br />
<br />
=== Scrolling issues ===<br />
<br />
If you have issues scrolling with Shift-Page Up/Down in your terminal, the following will remove the smcup and rmcup capabilities for any term that reports itself as anything beginning with {{ic|xterm}}:<br />
<br />
set -ga terminal-overrides ',xterm*:smcup@:rmcup@'<br />
<br />
This tricks the terminal emulator into thinking tmux is a full screen application like pico or mutt[https://superuser.com/questions/310251/use-terminal-scrollbar-with-tmux], which will make the scrollback be recorded properly. Beware however, it will get a bit messed up when switching between windows/panes. Consider using tmux's native scrollback instead.<br />
<br />
=== Mouse scrolling ===<br />
<br />
{{Note|This interferes with selection buffer copying and pasting. To copy/paste to/from the selection buffer hold the shift key.}}<br />
<br />
If you want to scroll with your mouse wheel, ensure mode-mouse is on in .tmux.conf<br />
set -g mouse on<br />
<br />
You can set scroll History with:<br />
set -g history-limit 30000<br />
<br />
For mouse wheel scrolling as from tmux 2.1 try adding one or both of these to ~/.tmux.conf<br />
bind -T root WheelUpPane if-shell -F -t = "#{alternate_on}" "send-keys -M" "select-pane -t =; copy-mode -e; send-keys -M"<br />
bind -T root WheelDownPane if-shell -F -t = "#{alternate_on}" "send-keys -M" "select-pane -t =; send-keys -M"<br />
<br />
Though the above will only scroll one line at a time, add this solution to scroll an entire page instead<br />
bind -t vi-copy WheelUpPane page-up<br />
bind -t vi-copy WheelDownPane page-down<br />
bind -t emacs-copy WheelUpPane page-up<br />
bind -t emacs-copy WheelDownPane page-down<br />
<br />
=== Terminal emulator does not support UTF-8 mouse events ===<br />
<br />
When the terminal emulator does not support the UTF-8 mouse events and the {{ic|mouse on}} tmux option is set, left-clicking inside the terminal window might paste strings like {{ic|[M#}} or {{ic|[Ma}} into the promt.<br />
<br />
To solve this issue set:<br />
<br />
set -g mouse-utf8 off<br />
<br />
=== Shift+F6 not working in Midnight Commander ===<br />
<br />
See [[Midnight Commander#Broken shortcuts]].<br />
<br />
== See also ==<br />
<br />
* [https://bbs.archlinux.org/viewtopic.php?id=84157&p=1 BBS topic]<br />
* [http://www.dayid.org/os/notes/tm.html Screen and tmux feature comparison]<br />
* [https://github.com/Lokaltog/powerline powerline], a dynamic statusbar for tmux<br />
* [https://github.com/tmux-plugins Plugins for tmux]<br />
* [https://github.com/gpakosz/.tmux Oh My Tmux!]<br />
<br />
'''Tutorials'''<br />
<br />
* [https://mutelight.org/practical-tmux Practical Tmux]<br />
* manual page {{man|1|tmux}}<br />
* [https://blog.hawkhost.com/2010/06/28/tmux-the-terminal-multiplexer/ Tmux tutorial Part 1] and [https://blog.hawkhost.com/2010/07/02/tmux-%E2%80%93-the-terminal-multiplexer-part-2 Part 2]<br />
* [https://leanpub.com/the-tao-of-tmux/read ''The Tao of tmux''], an ebook by Tony Narlock, author of [https://tmuxp.git-pull.com tmuxp] and [https://libtmux.git-pull.com libtmux]</div>Fethbitahttps://wiki.archlinux.org/index.php?title=Tmux&diff=731275Tmux2022-06-01T13:54:35Z<p>Fethbita: Added a new code snippet to show how to start attach tmux if systemd is being used to start a session</p>
<hr />
<div>{{Lowercase title}}<br />
[[Category:Terminal multiplexers]]<br />
[[de:Tmux]]<br />
[[ja:Tmux]]<br />
[[zh-hans:Tmux]]<br />
[https://tmux.github.io/ tmux] is a "terminal multiplexer: it enables a number of terminals (or windows), each running a separate program, to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached." <br />
<br />
tmux is an ISC-licensed alternative to [[GNU Screen]]. Although similar, there are many differences between the programs, as noted on the [https://github.com/tmux/tmux/wiki/FAQ tmux FAQ page].<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|tmux}} package.<br />
Optionally, install {{AUR|tmux-bash-completion-git}} to provide bash completion functions for tmux.<br />
<br />
== Configuration ==<br />
<br />
By default, tmux looks for user-specific configuration at {{ic|~/.tmux.conf}}, though {{ic|~/.config/tmux/tmux.conf}} (hardcoded, {{ic|$XDG_CONFIG_HOME}} is ignored) works too. A global configuration file may be provided at {{ic|/etc/tmux.conf}} though by default Arch does not ship such a file.<br />
<br />
=== Key bindings ===<br />
<br />
By default, command key bindings are prefixed by {{ic|Ctrl+b}}. For example, to vertically split a window type {{ic|Ctrl+b %}}.<br />
<br />
After splitting a window into multiple panes, a pane can be resized by the hitting prefix key (e.g. {{ic|Ctrl+b}}) and, while continuing to hold {{ic|Ctrl}}, press Left/Right/Up/Down. Swapping panes is achieved in the same manner, but by hitting ''o'' instead of a directional key.<br />
<br />
Key bindings may be changed with the bind and unbind commands in {{ic|tmux.conf}}. For example, the default prefix binding of {{ic|Ctrl+b}} can be changed to {{ic|Ctrl+a}} by adding the following commands in your configuration file:<br />
<br />
{{bc|<br />
unbind C-b<br />
set -g prefix C-a<br />
bind C-a send-prefix<br />
}}<br />
<br />
{{Tip|Quote special characters to use them as prefix. You may also use {{ic|Alt}} (called Meta) instead of {{ic|Ctrl}}. For example: {{ic|set -g prefix m-'\'}}}}<br />
<br />
To create a new window you can use {{ic|Ctrl+b c}} and move forward one window with {{ic|Ctrl+b n}} and backwards one window with {{ic|Ctrl+b p}}.<br />
<br />
Additional ways to move between windows include the following:<br />
<br />
Ctrl+b l (Move to the previously selected window)<br />
Ctrl+b w (List all windows / window numbers)<br />
Ctrl+b <window number> (Move to the specified window number, the default bindings are from 0 – 9)<br />
Ctrl+b q (Show pane numbers, when the numbers show up type the key to goto that pane)<br />
<br />
tmux has a find-window option & key binding to ease navigation of many windows:<br />
<br />
Ctrl+b f <window name> (Search for window name)<br />
Ctrl+b w (Select from interactive list of windows)<br />
<br />
==== Copy Mode ====<br />
<br />
A tmux window may be in one of several modes. The default permits direct access to the terminal attached to the window; the other is copy mode. Once in copy mode you can navigate the buffer including scrolling the history. Use [[vi]] or [[emacs]]-style key bindings in copy mode. The default is emacs, unless VISUAL or EDITOR contains ‘vi’<br />
<br />
To enter copy mode do the following:<br />
<br />
Ctrl+b [<br />
<br />
You can navigate the buffer as you would in your default editor.<br />
<br />
To quit copy mode, use one of the following keybindings:<br />
<br />
vi mode:<br />
q<br />
emacs mode:<br />
Esc<br />
<br />
=== Browsing URLs ===<br />
<br />
To browse URLs inside tmux you must have {{AUR|urlview}} installed and configured.<br />
<br />
Inside a new terminal:<br />
bind-key u capture-pane \; save-buffer /tmp/tmux-buffer \; run-shell "$TERMINAL -e urlview /tmp/tmux-buffer"<br />
<br />
Or inside a new tmux window (no new terminal needed):<br />
bind-key u capture-pane \; save-buffer /tmp/tmux-buffer \; new-window -n "urlview" '$SHELL -c "urlview < /tmp/tmux-buffer"'<br />
<br />
=== Setting the correct term ===<br />
<br />
==== 256 colors ====<br />
<br />
If you are using a 256 colour terminal, you will need to set the correct term in tmux. As of [https://raw.githubusercontent.com/tmux/tmux/master/CHANGES tmux 2.1], this is now ''tmux'', or ''tmux-256color''. You can do this in {{ic|tmux.conf}}:<br />
<br />
set -g default-terminal "tmux-256color" <br />
<br />
Other, older alternatives, include ''screen'', or ''screen-256color'':<br />
<br />
set -g default-terminal "screen-256color"<br />
<br />
Also, if tmux messes up, you can force tmux to assume that the terminal support 256 colors, by adding this in your .bashrc:<br />
<br />
alias tmux="tmux -2"<br />
<br />
==== 24-bit color ====<br />
<br />
tmux supports 24-bit color as of version 2.2 [https://github.com/tmux/tmux/commit/427b8204268af5548d09b830e101c59daa095df9]. If your terminal supports 24-bit color (see this [https://gist.github.com/XVilka/8346728 gist]), add your terminal to the {{ic|terminal-overrides}} setting. For example, if you use [[Termite]], you would add:<br />
<br />
set -ga terminal-overrides ",xterm-termite:Tc"<br />
<br />
For other terminals, replace {{ic|xterm-termite}} with the relevant terminal type (stored in {{ic|$TERM}}). See the {{man|1|tmux}} man page for details about the {{ic|Tc}} terminfo extension.<br />
<br />
==== xterm-keys ====<br />
<br />
To enable xterm-keys in your {{ic|tmux.conf}}, you have to add the following line<br />
<br />
set-option -g xterm-keys on<br />
<br />
If you enable xterm-keys in your {{ic|tmux.conf}}, then you need to build a custom terminfo to declare the new escape codes or applications will not know about them. Compile the following with {{ic|tic}} and you can use "xterm-screen-256color" as your TERM:<br />
<br />
# A screen- based TERMINFO that declares the escape sequences<br />
# enabled by the tmux config "set-window-option -g xterm-keys".<br />
#<br />
# Prefix the name with xterm- since some applications inspect<br />
# the TERM *name* in addition to the terminal capabilities advertised.<br />
xterm-screen-256color|GNU Screen with 256 colors bce and tmux xterm-keys,<br />
<br />
# As of Nov'11, the below keys are picked up by<br />
# .../tmux/blob/master/trunk/xterm-keys.c:<br />
kDC=\E[3;2~, kEND=\E[1;2F, kHOM=\E[1;2H,<br />
kIC=\E[2;2~, kLFT=\E[1;2D, kNXT=\E[6;2~, kPRV=\E[5;2~,<br />
kRIT=\E[1;2C,<br />
<br />
# Change this to screen-256color if the terminal you run tmux in<br />
# doesn't support bce:<br />
use=screen-256color-bce,<br />
<br />
To check if your terminal support bce, you can use {{ic|tic -c}}:<br />
<br />
$ tic -c xterm-screen-256color <br />
"xterm-screen-256color", line 16, terminal 'xterm-screen-256color': resolution of use=screen-256color-bce failed<br />
<br />
To compile with tic:<br />
<br />
$ tic xterm-screen-256color <br />
<br />
The file will be compiled and saved in $HOME/.terminfo or in /usr/share/terminfo/ if run as root (and so available system-wide).<br />
<br />
=== Other Settings ===<br />
<br />
To limit the scrollback buffer to 10000 lines:<br />
set -g history-limit 10000<br />
<br />
Mouse can be toggled with<br />
bind-key m set-option -g mouse \; display "Mouse: #{?mouse,ON,OFF}"<br />
<br />
=== Autostart with systemd ===<br />
<br />
There are some notable advantages to starting a tmux server at startup.<br />
Notably, when you start a new tmux session, having the service already running reduces any delays in the startup.<br />
<br />
Furthermore, any customization attached to your tmux session will be retained and your tmux session can be made to persist even if you have never logged in, if you have some reason to do that (like a heavily scripted tmux configuration or shared user tmux sessions).<br />
<br />
The service below starts ''tmux'' for the specified user (i.e. start with {{ic|tmux@''username''.service}}):<br />
<br />
{{hc|/etc/systemd/system/tmux@.service|<nowiki><br />
[Unit]<br />
Description=Start tmux in detached session<br />
<br />
[Service]<br />
Type=forking<br />
User=%I<br />
ExecStart=/usr/bin/tmux new-session -s %u -d<br />
ExecStop=/usr/bin/tmux kill-session -t %u<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
{{Tip|You may want to add {{ic|1=WorkingDirectory=''custom_path''}} to customize working directory. If set to {{ic|~}}, the home directory of the user specified in {{ic|1=User=}} is used.}}<br />
<br />
Alternatively, you can place this file within your [[systemd/User]] directory (without {{ic|1=User=%I}} and by replacing {{ic|multi-user.target}} with {{ic|default.target}} in {{ic|WantedBy}}), for example {{ic|~/.config/systemd/user/tmux.service}}. This way the tmux service will start when you log in, unless you also enable [[systemd/User#Automatic start-up of systemd user instances]].<br />
<br />
== Session initialization ==<br />
<br />
You can have tmux open a session with preloaded windows by including those details in your {{ic|~/.tmux.conf}}:<br />
<br />
new -n WindowName Command<br />
neww -n WindowName Command<br />
neww -n WindowName Command<br />
<br />
To start a session with split windows (multiple panes), include the splitw command below the neww you would like to split; thus:<br />
<br />
new -s SessionName -n WindowName Command<br />
neww -n foo/bar foo<br />
splitw -v -p 50 -t 0 bar<br />
selectw -t 1 <br />
selectp -t 0<br />
<br />
would open 2 windows, the second of which would be named foo/bar and would be split vertically in half (50%) with foo running above bar. Focus would be in window 2 (foo/bar), top pane (foo).<br />
<br />
{{Note|Numbering for sessions, windows and panes starts at zero, unless you have specified a base-index of 1 in your {{ic|.conf}} }}<br />
<br />
To manage multiple sessions, source separate session files from your conf file:<br />
<br />
# initialize sessions<br />
bind F source-file ~/.tmux/foo<br />
bind B source-file ~/.tmux/bar<br />
<br />
== X clipboard integration ==<br />
<br />
{{Tip|The tmux plugin [https://github.com/tmux-plugins/tmux-yank tmux-yank] provides similar functionality.}}<br />
<br />
It is possible to copy a tmux selection to the X clipboard (and to X primary/secondary selections), and paste from the X clipboard into tmux. The following tmux configuration file snippet integrates the X clipboard/selection with the current tmux selection using the program {{Pkg|xsel}}:<br />
<br />
# Emacs style<br />
bind-key -T copy-mode y send-keys -X copy-pipe-and-cancel "xsel -i -p && xsel -o -p | xsel -i -b"<br />
bind-key C-y run "xsel -o | tmux load-buffer - ; tmux paste-buffer"<br />
<br />
# Vim style<br />
bind-key -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "xsel -i -p && xsel -o -p | xsel -i -b"<br />
bind-key p run "xsel -o | tmux load-buffer - ; tmux paste-buffer"<br />
<br />
Note that it may be necessary to unbind the previous window shortcut with {{ic|unbind p}} for the latter to work.<br />
<br />
{{Pkg|xclip}} could also be used for this purpose. Unlike xsel, it works better when printing a raw bitstream that does not fit the current locale. Nevertheless, it is neater to use xsel because xclip does not close {{ic|STDOUT}} after it has read from the tmux buffer. As such, tmux does not know that the copy task has completed, and continues to wait for xclip to terminate, thereby rendering tmux unresponsive. A workaround is to redirect {{ic|STDOUT}} to {{ic|/dev/null}}:<br />
<br />
# Vim style<br />
bind-key -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "xclip -i -sel clip > /dev/null"<br />
bind-key p run "xclip -o -sel clip | tmux load-buffer - ; tmux paste-buffer"<br />
<br />
=== Urxvt middle click ===<br />
<br />
{{Note|To use this, you need to enable mouse support}}<br />
<br />
There is an unofficial perl extension ([https://github.com/tmux/tmux/wiki/FAQ#how-do-i-copy-a-selection-from-tmux-to-the-systems-clipboard mentioned] in the official [https://github.com/tmux/tmux/wiki/FAQ FAQ]) to enable copying/pasting in and out of urxvt with tmux via Middle Mouse Clicking.<br />
<br />
First, you will need to download the perl script and place it into urxvts perl lib:<br />
<br />
{{bc|wget http://anti.teamidiot.de/static/nei/*/Code/urxvt/osc-xterm-clipboard<br />
mv osc-xterm-clipboard /usr/lib/urxvt/perl/|<br />
}}<br />
<br />
You will also need to enable that perl script in your .Xdefaults:<br />
<br />
{{hc|~/.Xdefaults|<br />
...<br />
*URxvt.perl-ext-common: osc-xterm-clipboard<br />
...<br />
}}<br />
<br />
Next, you want to tell tmux about the new function and enable mouse support (if you have not already):<br />
<br />
{{hc|~/.tmux.conf|<br />
...<br />
set-option -ga terminal-override ',rxvt-uni*:XT:Ms<nowiki>=</nowiki>\E]52;%p1%s;%p2%s\007'<br />
set -g mouse on<br />
...<br />
}}<br />
<br />
That's it. Be sure to end all instances of tmux before trying the new MiddleClick functionality.<br />
<br />
While in tmux, Shift+MiddleMouseClick will paste the clipboard selection while just MiddleMouseClick will paste your tmux buffer.<br />
Outside of tmux, just use MiddleMouseClick to paste your tmux buffer and your standard {{ic|Ctrl+c}} to copy.<br />
<br />
== Tips and tricks ==<br />
<br />
=== Start tmux with default session layout ===<br />
<br />
Session managers like ''tmuxinator'' and [[tmuxp]] make it easy to manage common session configurations.<br />
<br />
For ''tmuxinator'', install {{AUR|tmuxinator}}. Test your installation with<br />
<br />
$ tmuxinator doctor<br />
<br />
==== Get the default layout values ====<br />
<br />
Start tmux as usual and configure your windows and panes layout as you like. When finished, get the current layout values by executing (while you are still within the current tmux session)<br />
<br />
tmux list-windows<br />
<br />
The output may look like this (two windows with 3 panes and 2 panes layout)<br />
<br />
0: default* (3 panes) [274x83] [layout 20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}] @2 (active)<br />
1: remote- (2 panes) [274x83] [layout e3d3,274x83,0,0[274x41,0,0,4,274x41,0,42,7]] @3 <br />
<br />
The Interesting part you need to copy for later use begins after '''[layout...''' and excludes '''... ] @2 (active)'''. For the first window layout you need to copy e.g. '''20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}'''<br />
<br />
==== Define the default tmux layout ====<br />
<br />
Knowing this, you can exit the current tmux session. Following this, you create your default tmux session layout by editing tmuxinator's configuration file (Do not copy the example, get your layout values as described above)<br />
<br />
{{hc|~/.tmuxinator/default.yml|<nowiki><br />
name: default<br />
root: ~/<br />
windows:<br />
- default:<br />
layout: 20a0,274x83,0,0{137x83,0,0,3,136x83,138,0[136x41,138,0,5,136x41,138,42,6]}<br />
panes:<br />
- clear<br />
- vim<br />
- clear && emacs -nw<br />
- remote:<br />
layout: 24ab,274x83,0,0{137x83,0,0,3,136x83,138,0,4}<br />
panes:<br />
- <br />
- <br />
</nowiki>}}<br />
<br />
The example defines two windows named "default" and "remote". With your determined layout values. For each pane you have to use at least one {{ic|-}} line. Within the first window panes you start the commandline "clear" in pane one, "vim" in pane two and "clear && emacs -nw" executes two commands in pane three on each tmux start. The second window layout has two panes without defining any start commmands.<br />
<br />
Test the new default layout with (yes, it is "mux"):<br />
<br />
mux default<br />
<br />
==== Autostart tmux with default tmux layout ====<br />
<br />
If you like to start your terminal session with your default tmux session layout edit<br />
{{hc|~/.bashrc|<nowiki><br />
if [ -z "$TMUX" ]; then<br />
mux default <br />
fi <br />
</nowiki>}}<br />
<br />
==== Alternate approach for default session ====<br />
<br />
Instead of using the above method, one can just write a bash script that when run, will create the default session and attach to it.<br />
Then you can execute it from a terminal to get the pre-designed configuration in that terminal<br />
<br />
#!/bin/bash<br />
tmux new-session -d -n WindowName Command<br />
tmux new-window -n NewWindowName<br />
tmux split-window -v<br />
tmux selectp -t 1<br />
tmux split-window -h<br />
tmux selectw -t 1<br />
tmux -2 attach-session -d<br />
<br />
=== Start tmux in urxvt ===<br />
<br />
Use this command to start urxvt with a started tmux session. I use this with the exec command from my .ratpoisonrc file.<br />
{{bc|<nowiki>urxvt -e bash -c "tmux -q has-session && exec tmux attach-session -d || exec tmux new-session -n$USER -s$USER@$HOSTNAME"</nowiki>}}<br />
<br />
=== Start tmux on every shell login ===<br />
<br />
The following snippet starts a session if one is not already present. Otherwise, tmux attaches to the preexisting session. <br />
{{bc|<nowiki><br />
# if tmux is executable and not inside a tmux session, then try to attach.<br />
# if attachment fails, start a new session<br />
[ -x "$(command -v tmux)" ] \<br />
&& [ -z "${TMUX}" ] \<br />
&& { tmux attach || tmux; } >/dev/null 2>&1<br />
</nowiki>}}<br />
<br />
Note that the above snippet causes tmux to launch in ''any'' login shell, including the virtual console. This interferes with [[Xinit#Autostart X at login]]. <br />
<br />
To launch tmux only when there is a graphical environment running, use this instead:<br />
<br />
{{bc|<nowiki><br />
# if tmux is executable, X is running, and not inside a tmux session, then try to attach.<br />
# if attachment fails, start a new session<br />
if [ -x "$(command -v tmux)" ] && [ -n "${DISPLAY}" ]; then<br />
[ -z "${TMUX}" ] && { tmux attach || tmux; } >/dev/null 2>&1<br />
fi<br />
</nowiki>}}<br />
<br />
If you are using [[#Autostart with systemd|systemd as a user to keep a session alive]], you can use the following snippet to attach to that session and detach all the other connected clients:<br />
<br />
{{bc|<nowiki><br />
# if tmux is executable and not inside a tmux session, and systemctl service is running try to attach.<br />
# if attachment fails, start the systemctl service<br />
[ -x "$(command -v tmux)" ] \<br />
&& [ -z "${TMUX}" ] \<br />
&& { systemctl --user is-active --quiet tmux.service && exec tmux attach-session -d -t "${USER}" || systemctl --user start tmux.service ; exec tmux attach-session -d -t "${USER}"; } >/dev/null 2>&1<br />
</nowiki>}}<br />
<br />
=== Start a non-login shell ===<br />
<br />
tmux starts a [[login shell]] [https://www.mail-archive.com/tmux-users@lists.sourceforge.net/msg05901.html by default], which may result in multiple negative side effects:<br />
<br />
* Users of [[Wikipedia:fortune (Unix)|fortune]] may notice that quotes are printed when creating a new panel.<br />
* The configuration files for login shells such as {{ic|~/.profile}} are interpreted each time a new panel is created, so commands intended to be run on session initialization (e.g. setting audio level) are executed.<br />
<br />
To disable this behaviour, add to {{ic|~/.tmux.conf}}:<br />
<br />
set -g default-command "${SHELL}"<br />
<br />
=== Use tmux windows like tabs ===<br />
<br />
The following settings added to {{ic|~/.tmux.conf}} allow to use tmux windows like tabs, such as those provided by the reference of these hotkeys — [[Rxvt-unicode/Tips_and_tricks#urxvtq_with_tabbing|urxvt's tabbing extensions]]. An advantage thereof is that these virtual “tabs” are independent of the terminal emulator.<br />
<br />
#urxvt tab like window switching (-n: no prior escape seq)<br />
bind -n S-down new-window<br />
bind -n S-left prev<br />
bind -n S-right next<br />
bind -n C-left swap-window -t -1<br />
bind -n C-right swap-window -t +1<br />
<br />
Of course, those should not overlap with other applications' hotkeys, such as the terminal's. Given that they substitute terminal tabbing that might as well be deactivated, though.<br />
<br />
It can also come handy to supplement the EOT hotkey {{ic|Ctrl+d}} with one for tmux's detach:<br />
<br />
bind-key -n C-j detach<br />
<br />
=== Clients simultaneously interacting with various windows of a session ===<br />
<br />
In [https://mutelight.org/practical-tmux#section-6 Practical Tmux], Brandur Leach writes:<br />
<br />
: Screen and tmux's behaviour for when multiple clients are attached to one session differs slightly. In Screen, each client can be connected to the session but view different windows within it, but in tmux, all clients connected to one session must view the same window.<br />
: This problem can be solved in tmux by spawning two separate sessions and synchronizing the second one to the windows of the first, then pointing a second new session to the first.<br />
<br />
The {{ic|tmx}} script below implements this — the version here is slightly modified to execute {{ic|tmux new-window}} if {{ic|1}} is its second parameter. Invoked as {{ic|tmx ''base_session_name'' [1]}}, it launches the base session if necessary. Otherwise a new "client" session linked to the base, optionally add a new window and attach, setting it to kill itself once it turns "zombie". Don't forget to make it [[executable]].<br />
<br />
{{hc|~/bin/tmx|2=<nowiki><br />
#!/bin/bash<br />
<br />
#<br />
# Modified TMUX start script from:<br />
# http://forums.gentoo.org/viewtopic-t-836006-start-0.html<br />
#<br />
#<br />
<br />
# Works because bash automatically trims by assigning to variables and by <br />
# passing arguments<br />
trim() { echo $1; }<br />
<br />
if [[ -z "$1" ]]; then<br />
echo "Specify session name as the first argument"<br />
exit<br />
fi<br />
<br />
# Only because I often issue `ls` to this script by accident<br />
if [[ "$1" == "ls" ]]; then<br />
tmux ls<br />
exit<br />
fi<br />
<br />
base_session="$1"<br />
# This actually works without the trim() on all systems except OSX<br />
tmux_nb=$(trim `tmux ls | grep "^$base_session" | wc -l`)<br />
if [[ "$tmux_nb" == "0" ]]; then<br />
echo "Launching tmux base session $base_session ..."<br />
tmux new-session -s $base_session<br />
else<br />
# Make sure we are not already in a tmux session<br />
if [[ -z "$TMUX" ]]; then<br />
echo "Launching copy of base session $base_session ..."<br />
# Session id is date and time to prevent conflict<br />
session_id=`date +%Y%m%d%H%M%S`<br />
# Create a new session (without attaching it) and link to base session <br />
# to share windows<br />
tmux new-session -d -t $base_session -s $session_id<br />
if [[ "$2" == "1" ]]; then<br />
# Create a new window in that session<br />
tmux new-window<br />
fi<br />
# Attach to the new session & kill it once orphaned<br />
tmux attach-session -t $session_id \; set-option destroy-unattached<br />
fi<br />
fi<br />
</nowiki>}}<br />
<br />
A useful setting for this is<br />
<br />
setw -g aggressive-resize on<br />
<br />
added to {{ic|~/.tmux.conf}}. It causes tmux to resize a window based on the smallest client actually viewing it, not on the smallest one attached to the entire session.<br />
<br />
An alternative taken from [http://comments.gmane.org/gmane.comp.terminal-emulators.tmux.user/2632]{{Dead link|2021|11|08|status=522}} is to put the following {{ic|~/.bashrc}}:<br />
<br />
{{hc|~/.bashrc|2=<nowiki><br />
function rsc() {<br />
CLIENTID=$1.`date +%S`<br />
tmux new-session -d -t $1 -s $CLIENTID \; set-option destroy-unattached \; attach-session -t $CLIENTID<br />
}<br />
<br />
function mksc() {<br />
tmux new-session -d -s $1<br />
rsc $1<br />
}<br />
</nowiki>}}<br />
<br />
Citing the author:<br />
<br />
: "mksc foo" creates a always detached permanent client named "foo". It also calls "rsc foo" to create a client to newly created session. "rsc foo" creates a new client grouped by "foo" name. It has destroy-unattached turned on so when I leave it, it kills client.<br />
: Therefore, when my computer looses network connectivity, all "foo.something" clients are killed while "foo" remains. I can then call "rsc foo" to continue work from where I stopped.<br />
<br />
=== Correct the TERM variable according to terminal type ===<br />
<br />
Instead of [[#Setting the correct term|setting a fixed TERM variable in tmux]], it is possible to set the proper TERM (either {{ic|screen}} or {{ic|screen-256color}}) according to the type of your terminal emulator:<br />
<br />
{{hc|~/.tmux.conf|<br />
## set the default TERM<br />
set -g default-terminal screen<br />
<br />
## update the TERM variable of terminal emulator when creating a new session or attaching a existing session<br />
set -g update-environment 'DISPLAY SSH_ASKPASS SSH_AGENT_PID SSH_CONNECTION WINDOWID XAUTHORITY TERM'<br />
## determine if we should enable 256-colour support<br />
if "[[ ${TERM} =~ 256color || ${TERM} == fbterm ]]" 'set -g default-terminal screen-256color'<br />
}}<br />
<br />
{{hc|1=~/.zshrc|2=<br />
## workaround for handling TERM variable in multiple tmux sessions properly from https://sourceforge.net/p/tmux/mailman/message/32751663/{{Dead link|2020|04|03|status=404}} by Nicholas Marriott<br />
if [[ -n ${TMUX} && -n ${commands[tmux]} ]];then<br />
case $(tmux showenv TERM 2>/dev/null) in<br />
*256color) ;&<br />
TERM=fbterm)<br />
TERM=screen-256color ;;<br />
*)<br />
TERM=screen<br />
esac<br />
fi<br />
}}<br />
<br />
=== Reload an updated configuration without restarting tmux ===<br />
<br />
By default tmux reads {{ic|~/.tmux.conf}} only if it was not already running. To have tmux load a configuration file afterwards, execute:<br />
<br />
tmux source-file <path><br />
<br />
This can be added to {{ic|~/.tmux.conf}} as e. g.:<br />
<br />
bind r source-file <path><br />
<br />
You can also do ^: and type :<br />
source .tmux.conf<br />
<br />
=== Template script to run program in new session or attach to existing one ===<br />
<br />
This script checks for a program presumed to have been started by a previous run of itself. Unless found it creates a new tmux session and attaches to a window named after and running the program. If however the program was found it merely attaches to the session and selects the window.<br />
<br />
#!/bin/bash<br />
<br />
PID=$(pidof $1)<br />
<br />
if [ -z "$PID" ]; then<br />
tmux new-session -d -s main ;<br />
tmux new-window -t main -n $1 "$*" ;<br />
fi<br />
tmux attach-session -d -t main ;<br />
tmux select-window -t $1 ;<br />
exit 0<br />
<br />
A derived version to run ''irssi'' with the ''nicklist'' plugin can be found on [[Irssi#Irssi with nicklist in tmux|its ArchWiki page]].<br />
<br />
=== Terminal emulator window titles ===<br />
<br />
If you SSH into a host in a tmux window, you will notice the window title of your terminal emulator remains to be {{ic|user@localhost}} rather than {{ic|user@server}}. To allow the title bar to adapt to whatever host you connect to, set the following in {{ic|~/.tmux.conf}}<br />
<br />
set -g set-titles on<br />
set -g set-titles-string "#T"<br />
<br />
For {{ic|set-titles-string}}, {{ic|#T}} will display {{ic|user@host:~}} and change accordingly as you connect to different hosts.<br />
<br />
=== Automatic layouting ===<br />
<br />
When creating new splits or destroying older ones the currently selected layout is not applied. To fix that, add following binds which will apply the currently selected layout to new or remaining panes:<br />
<br />
bind-key -n M-c kill-pane \; select-layout<br />
bind-key -n M-n split-window \; select-layout<br />
<br />
{{Tip|You may be interested in {{AUR|tmux-xpanes}} which makes managing window layouts and SSH connections easy.}}<br />
<br />
=== Vim colorscheme not loading ===<br />
<br />
See the following if your vim colorscheme is not loading in tmux: [https://stackoverflow.com/a/47994805] [https://github.com/vim/vim/issues/993#issuecomment-255651605]<br />
<br />
=== Vim friendly configuration ===<br />
<br />
See [https://gist.github.com/Lartza/6a7a62466a8a3e436234412d9b1c5066] for a configuration friendly to [[vim]] users.<br />
<br />
=== Friendly pane splitting ===<br />
<br />
The default key-binding for splitting a pane vertically is {{ic|Ctrl+b %}} and for splitting a pane horizontally is {{ic|Ctrl+b "}}. That can be difficult to type depending of your keyboard layout and it is also hard to remember.<br />
<br />
A more friendly key-binding is to use {{ic|Ctrl+b h}} for splitting horizontally and {{ic|Ctrl+b v}} for splitting a pane vertically, it is also very convenient to remember.<br />
<br />
To make this change, add these lines in {{ic|~/.tmux.conf}}:<br />
<br />
{{bc|<br />
# More friendly split pane<br />
bind-key h split-window -h<br />
bind-key v split-window -v<br />
}}<br />
<br />
=== Inhibit system suspension ===<br />
<br />
If tmux hangs when connected from another device because the host goes to sleep, run session's shell command with an inhibition lock:<br />
<br />
tmux new-session -A "systemd-inhibit --what=idle $SHELL"<br />
<br />
== Troubleshooting ==<br />
<br />
=== Scrolling issues ===<br />
<br />
If you have issues scrolling with Shift-Page Up/Down in your terminal, the following will remove the smcup and rmcup capabilities for any term that reports itself as anything beginning with {{ic|xterm}}:<br />
<br />
set -ga terminal-overrides ',xterm*:smcup@:rmcup@'<br />
<br />
This tricks the terminal emulator into thinking tmux is a full screen application like pico or mutt[https://superuser.com/questions/310251/use-terminal-scrollbar-with-tmux], which will make the scrollback be recorded properly. Beware however, it will get a bit messed up when switching between windows/panes. Consider using tmux's native scrollback instead.<br />
<br />
=== Mouse scrolling ===<br />
<br />
{{Note|This interferes with selection buffer copying and pasting. To copy/paste to/from the selection buffer hold the shift key.}}<br />
<br />
If you want to scroll with your mouse wheel, ensure mode-mouse is on in .tmux.conf<br />
set -g mouse on<br />
<br />
You can set scroll History with:<br />
set -g history-limit 30000<br />
<br />
For mouse wheel scrolling as from tmux 2.1 try adding one or both of these to ~/.tmux.conf<br />
bind -T root WheelUpPane if-shell -F -t = "#{alternate_on}" "send-keys -M" "select-pane -t =; copy-mode -e; send-keys -M"<br />
bind -T root WheelDownPane if-shell -F -t = "#{alternate_on}" "send-keys -M" "select-pane -t =; send-keys -M"<br />
<br />
Though the above will only scroll one line at a time, add this solution to scroll an entire page instead<br />
bind -t vi-copy WheelUpPane page-up<br />
bind -t vi-copy WheelDownPane page-down<br />
bind -t emacs-copy WheelUpPane page-up<br />
bind -t emacs-copy WheelDownPane page-down<br />
<br />
=== Terminal emulator does not support UTF-8 mouse events ===<br />
<br />
When the terminal emulator does not support the UTF-8 mouse events and the {{ic|mouse on}} tmux option is set, left-clicking inside the terminal window might paste strings like {{ic|[M#}} or {{ic|[Ma}} into the promt.<br />
<br />
To solve this issue set:<br />
<br />
set -g mouse-utf8 off<br />
<br />
=== Shift+F6 not working in Midnight Commander ===<br />
<br />
See [[Midnight Commander#Broken shortcuts]].<br />
<br />
== See also ==<br />
<br />
* [https://bbs.archlinux.org/viewtopic.php?id=84157&p=1 BBS topic]<br />
* [http://www.dayid.org/os/notes/tm.html Screen and tmux feature comparison]<br />
* [https://github.com/Lokaltog/powerline powerline], a dynamic statusbar for tmux<br />
* [https://github.com/tmux-plugins Plugins for tmux]<br />
* [https://github.com/gpakosz/.tmux Oh My Tmux!]<br />
<br />
'''Tutorials'''<br />
<br />
* [https://mutelight.org/practical-tmux Practical Tmux]<br />
* manual page {{man|1|tmux}}<br />
* [https://blog.hawkhost.com/2010/06/28/tmux-the-terminal-multiplexer/ Tmux tutorial Part 1] and [https://blog.hawkhost.com/2010/07/02/tmux-%E2%80%93-the-terminal-multiplexer-part-2 Part 2]<br />
* [https://leanpub.com/the-tao-of-tmux/read ''The Tao of tmux''], an ebook by Tony Narlock, author of [https://tmuxp.git-pull.com tmuxp] and [https://libtmux.git-pull.com libtmux]</div>Fethbitahttps://wiki.archlinux.org/index.php?title=OpenVAS&diff=599046OpenVAS2020-02-25T20:11:56Z<p>Fethbita: Dead link fixed, now points to architecture page for Openvas (like before it was killed.) [https://web.archive.org/web/20161010215527/http://www.greenbone.net/technology/openvas.html]</p>
<hr />
<div>[[Category:Networking]]<br />
[[Category:Security testing]]<br />
[[ja:OpenVAS]]<br />
{{Out of date|{{ic|openvas-manager}} was renamed to gvmd, command names have changed and instructions need to be updated to work with the latest version.}}<br />
{{Style|Various [[Help:Style]] issues}}<br />
[http://www.openvas.org/ OpenVAS] stands for Open Vulnerability Assessment System and is a network security scanner with associated tools like a graphical user front-end. The core component is a server with a set of network vulnerability tests (NVTs) to detect security problems in remote systems and applications. <br />
<br />
== Pre-install ==<br />
<br />
=== Redis ===<br />
<br />
Configure {{pkg|redis}} as prescribed by the [https://github.com/greenbone/openvas-scanner/blob/v5.0.9/doc/redis_config.txt OpenVAS redis configuration]. In summary, amend the following to your /etc/redis.conf<br />
<br />
unixsocket /var/lib/redis/redis.sock<br />
unixsocketperm 700<br />
port 0<br />
timeout 0<br />
databases 128<br />
<br />
{{Note|See the previous {{ic|OpenVAS redis configuration}} document on how to calculate the {{ic|databases}} number.}}<br />
<br />
Additionally comment out the following (and similar) {{ic|save}} lines if present to avoid a stuck connection of the {{ic|openvas-scanner}} to {{ic|redis}}:<br />
<br />
save 900 1<br />
save 300 10<br />
save 60 10000<br />
<br />
Create {{ic|/etc/openvas/openvassd.conf}} and add the following:<br />
<br />
db_address = /var/lib/redis/redis.sock<br />
<br />
Finally restart {{ic|redis}}:<br />
<br />
# systemctl restart redis<br />
<br />
=== haveged ===<br />
<br />
If running OpenVAS in a virtual machine or any other system having a low entropy, you can optionally [[install]] {{pkg|haveged}} to gather more entropy. This is required for the key material used for the encrypted credentials saved within the {{ic|openvas-manager}} database.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|openvas}} package from the [[official repositories]].<br />
<br />
Alternatively install {{Grp|greenbone-vulnerability-manager}} which provides {{Pkg|openvas}}, the Greenbone Vulnerability Manager ({{Pkg|gvmd}}) and Greenbone Security Assistant (gsa) {{Pkg|greenbone-security-assistant}}) OpenVAS web frontend.<br />
<br />
== Initial setup ==<br />
<br />
Create certificates for the server and clients, default values were used:<br />
<br />
# gvm-manage-certs -a<br />
<br />
Update the plugins and vulnerability data:<br />
<br />
# greenbone-nvt-sync<br />
# greenbone-scapdata-sync<br />
# greenbone-certdata-sync<br />
<br />
{{Note|If GSA complains that the scapdata database is missing, it may be necessary to use greenbone-scapdata-sync --refresh.}}<br />
<br />
Add an administrator user account, be sure to copy the password:<br />
<br />
# gvmd --create-user=admin --role=Admin<br />
<br />
You can also change the password of the user later on<br />
<br />
# gvmd --user=admin --new-password=<password><br />
<br />
== Getting started ==<br />
<br />
Start the {{ic|gvmd}} daemon<br />
<br />
# gvmd -p 9390 -a 127.0.0.1<br />
<br />
Start the [https://community.greenbone.net/t/about-gvm-architecture/1231 Greenbone Security Assistant] WebUI (optional)<br />
<br />
# gsad -f --listen=127.0.0.1 --mlisten=127.0.0.1 --mport=9390<br />
<br />
Point your web browser to http://127.0.0.1 and login with your admin crendentials<br />
<br />
{{Note|By default, {{ic|gsad}} will bind to port 80. If you are already running a webserver, this will obviously cause problems. Pass the {{ic|--port}} switch to {{ic|gsad}} for an alternate port. Read the {{ic|gsad}} man page for options like {{ic|--http-only}}, {{ic|--no-redirect}}, and more.}}<br />
{{Note|The [https://community.greenbone.net/t/about-gvm-architecture/1231 Greenbone Security Assistant] WebUI requires the {{grp|texlive-most}} package in order to provide PDF downloads of the reports.}}<br />
<br />
== Systemd ==<br />
<br />
Redhat based systemd units are in an AUR package named {{aur|openvas-systemd}}. The contain a few tweaks such as better TLS settings.<br />
<br />
== Migration to new major versions ==<br />
<br />
The database needs to be migrated when moving to a new major version:<br />
<br />
# gvmd --migrate<br />
<br />
== See also ==<br />
<br />
* [[Wikipedia:OpenVAS]]<br />
* [http://www.openvas.org/ OpenVAS] Official OpenVAS website.</div>Fethbitahttps://wiki.archlinux.org/index.php?title=OpenVAS&diff=583784OpenVAS2019-09-23T23:31:31Z<p>Fethbita: /* Redis */ Changed kb_location to db_address because "Setting 'kb_location' has been renamed to 'db_address'." (https://github.com/greenbone/openvas/issues/270#issuecomment-461025707)</p>
<hr />
<div>[[Category:Networking]]<br />
[[Category:Security testing]]<br />
[[ja:OpenVAS]]<br />
{{Out of date|{{ic|openvas-manager}} was renamed to gvmd, command names have changed and instructions need to be updated to work with the latest version.}}<br />
{{Style|Various [[Help:Style]] issues}}<br />
[http://www.openvas.org/ OpenVAS] stands for Open Vulnerability Assessment System and is a network security scanner with associated tools like a graphical user front-end. The core component is a server with a set of network vulnerability tests (NVTs) to detect security problems in remote systems and applications. <br />
<br />
== Pre-install ==<br />
<br />
=== Redis ===<br />
<br />
Configure {{pkg|redis}} as prescribed by the [https://github.com/greenbone/openvas-scanner/blob/v5.0.9/doc/redis_config.txt OpenVAS redis configuration]. In summary, amend the following to your /etc/redis.conf<br />
<br />
unixsocket /var/lib/redis/redis.sock<br />
unixsocketperm 700<br />
port 0<br />
timeout 0<br />
databases 128<br />
<br />
{{Note|See the previous {{ic|OpenVAS redis configuration}} document on how to calculate the {{ic|databases}} number.}}<br />
<br />
Additionally comment out the following (and similar) {{ic|save}} lines if present to avoid a stuck connection of the {{ic|openvas-scanner}} to {{ic|redis}}:<br />
<br />
save 900 1<br />
save 300 10<br />
save 60 10000<br />
<br />
Create {{ic|/etc/openvas/openvassd.conf}} and add the following:<br />
<br />
db_address = /var/lib/redis/redis.sock<br />
<br />
Finally restart {{ic|redis}}:<br />
<br />
# systemctl restart redis<br />
<br />
=== haveged ===<br />
<br />
If running OpenVAS in a virtual machine or any other system having a low entropy, you can optionally [[install]] {{pkg|haveged}} to gather more entropy. This is required for the key material used for the encrypted credentials saved within the {{ic|openvas-manager}} database.<br />
<br />
== Installation ==<br />
<br />
[[Install]] the {{Pkg|openvas}} package from the [[official repositories]].<br />
<br />
Alternatively install {{Grp|greenbone-vulnerability-manager}} which provides {{Pkg|openvas}}, the Greenbone Vulnerability Manager ({{Pkg|gvmd}}) and Greenbone Security Assistant (gsa) {{Pkg|greenbone-security-assistant}}) OpenVAS web frontend.<br />
<br />
== Initial setup ==<br />
<br />
Create certificates for the server and clients, default values were used:<br />
<br />
# gvm-manage-certs -a<br />
<br />
Update the plugins and vulnerability data:<br />
<br />
# greenbone-nvt-sync<br />
# greenbone-scapdata-sync<br />
# greenbone-certdata-sync<br />
<br />
{{Note|If GSA complains that the scapdata database is missing, it may be necessary to use greenbone-scapdata-sync --refresh.}}<br />
<br />
Add an administrator user account, be sure to copy the password:<br />
<br />
# gvmd --create-user=admin --role=Admin<br />
<br />
You can also change the password of the user later on<br />
<br />
# gvmd --user=admin --new-password=<password><br />
<br />
== Getting started ==<br />
<br />
Start the {{ic|gvmd}} daemon<br />
<br />
# gvmd -p 9390 -a 127.0.0.1<br />
<br />
Start the [http://www.greenbone.net/technology/openvas.html Greenbone Security Assistant] WebUI (optional)<br />
<br />
# gsad -f --listen=127.0.0.1 --mlisten=127.0.0.1 --mport=9390<br />
<br />
Point your web browser to http://127.0.0.1 and login with your admin crendentials<br />
<br />
{{Note|By default, {{ic|gsad}} will bind to port 80. If you are already running a webserver, this will obviously cause problems. Pass the {{ic|--port}} switch to {{ic|gsad}} for an alternate port. Read the {{ic|gsad}} man page for options like {{ic|--http-only}}, {{ic|--no-redirect}}, and more.}}<br />
{{Note|The [http://www.greenbone.net/technology/openvas.html Greenbone Security Assistant] WebUI requires the {{grp|texlive-most}} package in order to provide PDF downloads of the reports.}}<br />
<br />
== Systemd ==<br />
<br />
Redhat based systemd units are in an AUR package named {{aur|openvas-systemd}}. The contain a few tweaks such as better TLS settings.<br />
<br />
== Migration to new major versions ==<br />
<br />
The database needs to be migrated when moving to a new major version:<br />
<br />
# gvmd --migrate<br />
<br />
== See also ==<br />
<br />
* [[Wikipedia:OpenVAS]]<br />
* [http://www.openvas.org/ OpenVAS] Official OpenVAS website.</div>Fethbita