Инструменты пользователя

Инструменты сайта


linux:ssh:key

Различия

Здесь показаны различия между двумя версиями данной страницы.

Ссылка на это сравнение

Предыдущая версия справа и слева Предыдущая версия
Следующая версия
Предыдущая версия
linux:ssh:key [2021/10/30 19:36]
werwolf
linux:ssh:key [2023/11/12 11:24] (текущий)
werwolf
Строка 1: Строка 1:
-===== SSH =====+====== Авторизация по ключу ​SSH ======
  
-Ключи SSH могут служить средством идентификации вас на сервере SSH с помощью [[https://​en.wikipedia.org/​wiki/​Public-key_cryptography|public-key cryptography]] and [[https://​en.wikipedia.org/​wiki/​Challenge-response_authentication|challenge-response authentication]]. ​ Основным преимуществом аутентификации на основе ключей является то, что в отличие от аутентификации по паролю она не подвержена [[https://​en.wikipedia.org/​wiki/​Brute-force_attack|brute-force attacks]] и вы не предоставляете действительные учетные данные,​ если сервер был скомпрометирован ( [[https://​tools.ietf.org/​html/​rfc4251#​section-9.4.4|RFC 4251 9.4.4]]). 
  
-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.+===== Как работают ключи ​SSH? =====
  
-Key-based authentication is not without its drawbacks and may not be appropriate for all environmentsbut in many circumstances it can offer some strong advantagesA general understanding of how SSH keys work will help you decide how and when to use them to meet your needs.+SSH сервер может выполнять аутентификацию пользователей с помощью различных алгоритмов. Самый популярный ​это аутентификация по паролю. Он достаточно простно не очень безопасныйПароли передаются по безопасному каналу,​ но они недостаточно сложны для противостояния попыткам перебора. Вычислительная мощность современных систем в сочетании со специальными скриптами делают перебор очень простым. Конечно,​ существуют другие способы дополнительной безопасности,​ например,​ fail2ban, но аутентификация по ключу ​SSH более надежна.
  
-This article assumes you already have a basic understanding of the [[:​title:​secure_shell|Secure Shell]] protocol and have [[:​title:​install|installed]] the [[https://​archlinux.org/​packages/?​name=openssh|openssh]] package.+Каждая пара ключей состоит из открытого и закрытого ключаСекретный ключ сохраняется на стороне клиента и не должен быть доступен кому-либо еще. Утечка ключа позволит злоумышленнику войти на сервер,​ если не была настроена дополнительная аутентификация по паролю.
  
-===== Background =====+Открытый ключ используется для шифрования сообщений,​ которые можно расшифровать только закрытым ключом. Это свойство и используется для аутентификации с помощью пары ключей. Открытый ключ загружается на удаленный сервер,​ к которому необходимо получить доступ. Его нужно добавить в специальный файл ~/​.ssh/​authorized_keys.
  
-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 contrastthe public key can be shared freely with any SSH server to which you wish to connect.+Когда клиент попытается выполнить проверку подлинности через этот ключсервер отправит сообщение,​ зашифрованное с помощью открытого ключа, если клиент сможет его расшифровать и вернуть правильный ответ - аутентификация пройдена.
  
-If an SSH server has your public key on file and sees you requesting a connection, it uses your public key to construct and send you a challenge. This challenge is an encrypted message and it must be met with the appropriate response before the server will grant you access. What makes this coded message particularly secure is that it can only be understood by the private key holder. While the public key can be used to encrypt the message, it cannot be used to decrypt that very same message. Only you, the holder of the private key, will be able to correctly understand the challenge and produce the proper response.+{{ :​linux:​ssh:​fetch.png |}} 
 +===== Как создать ключи ​SSH? =====
  
-This [[https://​en.wikipedia.org/​wiki/​Challenge-response_authentication|challenge-response]] phase happens behind the scenes and is invisible to the user. As long as you hold the private keywhich is typically stored in the ''​~/​.ssh/''​ directoryyour SSH client should be able to reply with the appropriate response to the server.+Сначала необходимо создать ключи ssh для аутентификации на локальном сервереДля этого существует специальная утилита ssh-keygenкоторая входит в набор утилит OpenSSHПо умолчанию она создает пару 2048 битных RSA ключейкоторая подойдет не только для ​SSH, но и для большинства других ситуаций.
  
-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 requireda 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.+И такгенерация ключей ssh выполняется командой:​
  
-===== Generating an SSH key pair ===== +<​code ​bash
- +ssh-keygen
-An SSH key pair can be generated by running the ''​ssh-keygen''​ command, defaulting to 3072-bit RSA (and SHA256) which the [[https://​man.archlinux.org/​man/​ssh-keygen.1|ssh-keygen(1)]] man page says is "//​generally considered sufficient//"​ and should be compatible with virtually all clients and servers:<​code>​ +
-ssh-keygen+
 </​code>​ </​code>​
  
-<​code>​ +{{ :linux:ssh:fetch_2.png |}}
-Generating public/​private rsa key pair. +
-Enter file in which to save the key (/​home/<​username>/​.ssh/​id_rsa): +
-Enter passphrase (empty for no passphrase): +
-Enter same passphrase again: +
-Your identification has been saved in /​home/<​username>/​.ssh/id_rsa. +
-Your public key has been saved in /​home/<​username>/​.ssh/​id_rsa.pub. +
-The key fingerprint is: +
-SHA256:​gGJtSsV8BM+7w018d39Ji57F8iO6c0N2GZq3/​RY2NhI username@hostname +
-The key's randomart image is: +
-+---[RSA 3072]----+ +
-|   ooo         | +
-|   ​oo+. ​         | +
-|  + +.+          | +
-| o +   ​+ ​    E . | +
-|  .   . S . . =.o| +
-|     . + . . B+@o| +
-|      + .   ​oo*=O| +
-|       ​. ​  ​..+=o+| +
-|           ​o=ooo+| +
-+----[SHA256]-----+ +
-</​code>​+
  
-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.+Утилита предложит вам выбрать расположение ключейПо умолчанию ключи располагаются в папке ​~/.ssh/. Лучше ничего не менять,​ чтобы все работало по умолчанию и ключи автоматически подхватывалисьСекретный ключ будет называться id_rsa, а публичный id_rsa.pub.
  
-**Note:** You can use the ''​-a''​ switch to specify the number of KDF rounds on the password encryption.+Затем утилита предложит ввести пароль для дополнительного шифрования ключа на дискеЕго можно не указывать,​ если не хотите. Использование дополнительного шифрования имеет только один минус - необходимость вводить пароль,​ и несколько преимуществ:​
  
-You can also add an optional comment field to the public key with the ''​-C''​ switchto more easily identify it in places such as ''​~/​.ssh/​known_hosts''​''​~/​.ssh/​authorized_keys''​ and ''​ssh-add -L''​ outputFor example:<​code>​ +  * Пароль никогда не попадет в сетьон используется только на локальной машине для расшифровки ключаЭто значит что перебор по паролю больше невозможен. 
-$ ssh-keygen -C "​$(whoami)@$(uname -n)-$(date -I)" +  * Секретный ключ хранится в закрытом каталоге и у клиента ​ssh нет к нему доступа пока вы не введете пароль;​ 
-</​code>​+  * Если злоумышленник хочет взломать аутентификацию по ключу SSHему понадобится доступ к вашей системеИ даже тогда ключевая фраза может стать серьезной помехой на его пути.
  
-will add a comment saying which user created the key on which machine and when. 
  
-==== Choosing the authentication key type ==== 
  
-OpenSSH supports several signing algorithms (for authentication keys) which can be divided in two groups depending on the mathematical properties they exploit:+Но все же, это необязательное дополнение и если не хотите,​ то вы можете просто нажать Enter. Тогда доступ по ключу ssh будет выполняться автоматически и вам не нужно будет что-либо вводить.
  
-  - [[https://​en.wikipedia.org/​wiki/​Digital_Signature_Algorithm|DSA]] and [[https://​en.wikipedia.org/​wiki/​RSA_(cryptosystem)|RSA]],​ which rely on the [[https://​en.wikipedia.org/​wiki/​Integer_factorization#​Difficulty_and_complexity|practical difficulty]] of factoring the product of two large prime numbers, +Теперь у вас есть открытый и закрытый ключи SSH и вы можете использовать их для проверки подлинностиДальше нам осталось разместить открытый ключ на удаленном сервере.
-  - [[https://​en.wikipedia.org/​wiki/​Elliptic_Curve_Digital_Signature_Algorithm|ECDSA]] and [[https://​en.wikipedia.org/​wiki/​Curve25519|Ed25519]],​ which rely on the elliptic curve [[https://​en.wikipedia.org/​wiki/​Discrete_logarithm|discrete logarithm]] problem. ([[https://​www.certicom.com/​content/​certicom/​en/​52-the-elliptic-curve-discrete-logarithm-problem.html|example]])+
  
-[[https://​blog.cloudflare.com/​a-relatively-easy-to-understand-primer-on-elliptic-curve-cryptography/​|Elliptic curve cryptography]] (ECC) algorithms are a [[https://​en.wikipedia.org/​wiki/​Elliptic_curve_cryptography#​History|more recent addition]] to public key cryptosystems. One of their main advantages is their ability to provide [[https://​en.wikipedia.org/​wiki/​Elliptic_curve_cryptography#​Rationale|the same level of security with smaller keys]], which makes for less computationally intensive operations (//​i.e.// ​ faster key creation, encryption and decryption) and reduced storage and transmission requirements.+===== Загрузка ключа на сервер =====
  
-OpenSSH 7.0 [[https://​archlinux.org/​news/​openssh-70p1-deprecates-ssh-dss-keys/​|deprecated and disabled support for DSA keys]] due to discovered vulnerabilitiestherefore the choice of [[https://​en.wikipedia.org/​wiki/​cryptosystem|cryptosystem]] lies within RSA or one of the two types of ECC.+Когда генерация ключей завершена,​ нам осталось только загрузить ключ на серверДля загрузки ключа можно использовать несколько способовВ некоторых случаях вы можете указать ключ в панели управления сервером,​ напримерсPanel или любой другойНо мы такой способ рассматривать не будемМы рассмотрим ручные способы.
  
-[[#​rsa|#​RSA]] keys will give you the greatest portability,​ while [[#​ed25519|#​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|[1]]][[#​ecdsa|#​ECDSA]] is likely more compatible than Ed25519 (though still less than RSA), but suspicions exist about its security (see below).+Самый простой способ скопировать ключ на удаленный сервер ​это использовать утилиту ssh-copy-idОна тоже входит в пакет программ OpenSSHНо для работы этого метода вам нужно иметь пароль доступа к серверу по SSHСинтаксис команды:​
  
-**Note:​** ​ These keys are used only to authenticate you; choosing stronger keys will not increase CPU load when transferring data over SSH. +<​code ​bash
- +ssh-copy-id username@remote_host
-=== RSA === +
- +
-''​ssh-keygen'' ​ defaults to RSA therefore there is no need to specify it with the ''​-t'' ​ option. It provides the best compatibility of all algorithms but requires the key size to be larger to provide sufficient security. +
- +
-Minimum key size is 1024 bits, default is 3072 (see [[https://​man.archlinux.org/​man/​ssh-keygen.1|ssh-keygen(1)]]) and maximum is 16384. +
- +
-If you wish to generate a stronger RSA key pair (//​e.g.// ​ to guard against cutting-edge or unknown attacks and more sophisticated attackers), simply specify the ''​-b'' ​ option with a higher bit value than the default:<​code>​ +
-ssh-keygen ​-b 4096+
 </​code>​ </​code>​
  
-Be aware though that there are diminishing returns in using longer keys.[[https://​security.stackexchange.com/​a/​25377|[2]]][[https://​www.gnupg.org/​faq/​gnupg-faq.html#​no_default_of_rsa4096|[3]]] 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|[4]]]+{{ :linux:ssh:fetch_3.png |}}
  
-On the other handthe 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/​|[5]]]+При первом подключении к серверу система может его не распознатьпоэтому вам нужно ввести yesЗатем введите ваш пароль пользователя на удаленном сервереУтилита подключится к удаленному серверу,​ а затем использует содержимое ключа id.rsa.pub для загрузки его на сервер в файл ~/.ssh/authorized_keysДальше вы можете выполнять аутентификацию с помощью этого ключа.
  
-=== ECDSA ===+Если такой способ по какой-либо причине для вас не работает,​ вы можете скопировать ключ по ssh вручную. Мы создадим каталог ~/.ssh, а затем поместим наш ключ в файл authorized_keys с помощью символа >>, это позволит не перезаписывать существующие ключи:
  
-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. +<code bash> 
- +cat ~/.ssh/id_rsa.pub ssh username@remote_host ​"mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"​
-There are two sorts of concerns with it: +
- +
-  - //Political concerns//, the trustworthiness of NIST-produced curves [[https://crypto.stackexchange.com/​questions/​10263/​should-we-trust-the-nist-recommended-ecc-parameters|being questioned]] after revelations that the NSA willingly inserts backdoors into softwares, hardware components and published standards were made; well-known cryptographers [[https://www.schneier.com/​blog/​archives/​2013/​09/​the_nsa_is_brea.html#​c1675929|have]][[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/​|proved]] in the past. +
-  - //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. +
-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|#​Ed25519]] is technically superior and should therefore be preferred. +
- +
-=== Ed25519 === +
- +
-[[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|[6]]] See also [[https://​blog.mozilla.org/​warner/​2011/​11/​29/​ed25519-keys/​|this blog post]] by a Mozilla developer on how it works. +
- +
-It is already implemented in [[https://​en.wikipedia.org/​wiki/​Curve25519#​Popularity|many applications and libraries]] and is the [[https://​www.libssh.org/​2013/​11/​03/​openssh-introduces-curve25519-sha256libssh-org-key-exchange/​|default key exchange algorithm]] (which is different from key //​signature//​) in OpenSSH. +
- +
-Ed25519 key pairs can be generated with:<​code>​ +
-$ ssh-keygen -t ed25519+
 </​code>​ </​code>​
  
-There is no need to set the key sizeas all Ed25519 keys are 256 bits.+Здесь вам тоже нужно набрать yesесли вы подключаетесь к новому серверу,​ а затем ввести парольТеперь вы можете использовать созданный ключ для аутентификации на сервере:​
  
-Keep in mind that older SSH clients and servers may not support these keys. +<​code ​bash
- +ssh username@remote_host
-=== FIDO/U2F === +
- +
-FIDO/​[[:​title:​u2f|U2F]] [[https://​en.wikipedia.org/​wiki/​Security_Tokens|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. +
- +
-The [[https://​archlinux.org/​packages/?​name=libfido2|libfido2]] is required for hardware token support. +
- +
-**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 [[https://​man.archlinux.org/​man/​sshd_config.5#​SecurityKeyProvider|sshd_config(5) § SecurityKeyProvider]] directive or the ''​SSH_SK_PROVIDER'' ​ environment variable for ''​ssh-keygen'' ​ and ''​ssh-add''​. +
- +
-After attaching a compatible FIDO key, a key pair may be generated with:<​code>​ +
-ssh-keygen -t ed25519-sk+
 </​code>​ </​code>​
  
-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 ''​-O no-touch-required'' ​ command line option is used during generation and the [[https://​man.archlinux.org/​man/​sshd.8#​no-touch-required|sshd(8) § no-touch-required]] ''​authorized_keys'' ​ option is set on the server. Note that not all hardware tokens support this option. 
  
-An ECDSA-based keypair may also be generated with the ''​ecdsa-sk'' ​ keytypebut the relevant concerns in the [[#​ecdsa|#​ECDSA]] section above still apply.+Если вы не захотели создать ssh ключ с доступом по паролюто вы сразу же будете авторизованы,​ что очень удобно. Иначе, сначала вам придется ввести фразу-пароль для расшифровки ключа.
  
-Keep in mind that many SSH servers may not support these keys.+===== Отключение проверки пароля =====
  
-==== Choosing the key location and passphrase ====+Если пароль больше не будет использоваться,​ то для увеличения безопасности системы лучше его вовсе отключить. Но убедитесь,​ что ключ надежно сохранен и вы его не потеряете,​ потому что по паролю вы больше не войдете. Авторизуйтесь на сервере,​ затем откройте конфигурационный файл /​etc/​ssh/​sshd_config и найдите там директиву PasswordAuthenticatin. Нужно установить ее значение в No:
  
-Upon issuing the ''​ssh-keygen'' ​ command, you will be prompted for the desired name and location of your private key. By default, keys are stored in the ''​~/.ssh/'' ​ directory and named according to the type of encryption used. You are advised to accept the default name and location in order for later code examples in this article to work properly.+<code bash> 
 +sudo vi /etc/ssh/sshd_config
  
-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. +PasswordAuthentication no
- +
-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. +
- +
-**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. +
- +
-=== Changing the private key's passphrase without changing the key === +
- +
-If the originally chosen SSH key passphrase is undesirable or must be changed, one can use the ''​ssh-keygen'' ​ command to change the passphrase without changing the actual key. This can also be used to change the password encoding format to the new standard.<​code>​ +
-$ ssh-keygen -f ~/​.ssh/​id_rsa -p+
 </​code>​ </​code>​
  
-=== Managing multiple keys ===+{{ :​linux:​ssh:​fetch_4.png |}}
  
-If you have multiple SSH identities, you can set different keys to be used for different hosts or remote users by using the ''​Match'' ​ and ''​IdentityFile'' ​ directives in your configuration:+Теперь сохраните файл и перезапустите службу ssh:
  
-<​code>​ +<​code ​bash
-~/.ssh/config+sudo service ​ssh restart
 </​code>​ </​code>​
  
-<​code>​ +Дальше будет возможно только подключение по ключу ​ssh, пароль не будет приниматься.
-Match host=SERVER1 +
-   ​IdentitiesOnly yes +
-   ​IdentityFile ~/.ssh/​id_rsa_IDENTITY1 +
- +
-Match host=SERVER2,SERVER3 +
-   ​IdentitiesOnly yes +
-   ​IdentityFile ~/​.ssh/​id_ed25519_IDENTITY2 +
-</​code>​ +
- +
-See [[https://​man.archlinux.org/​man/​ssh_config.5|ssh_config(5)]] for full description of these options. +
- +
-=== Storing SSH keys on hardware tokens === +
- +
-[[:​title:​file:​tango-view-fullscreen|{{:​images:​3:​38:​tango-view-fullscreen.png?​nolink&​48x48|Tango-view-fullscreen.png}}]]**This article or section needs expansion.** ​ [[:​title:​file:​tango-view-fullscreen|{{:​images:​3:​38:​tango-view-fullscreen.png?​nolink&​48x48|Tango-view-fullscreen.png}}]] +
- +
-**Reason:​** ​ [[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. (Discuss in [[https://​wiki.archlinux.org/​title/​Talk:​SSH_keys|Talk:​SSH keys]]) +
- +
-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. +
- +
-Examples are hardware tokens are described in: +
- +
-  * [[:​title:​yubikey#​ssh_notes|YubiKey#​SSH notes]] Native OpenSSH support for FIDO/U2F keys +
-  * [[:​title:​yubikey#​ssh_keys|YubiKey#​SSH keys]] +
-  * [[:​title:​trusted_platform_module#​securing_ssh_keys|Trusted Platform Module#​Securing SSH keys]] +
- +
-===== Copying the public key to the remote server ===== +
- +
-[[:​title:​file:​tango-view-fullscreen|{{:​images:​3:​38:​tango-view-fullscreen.png?​nolink&​48x48|Tango-view-fullscreen.png}}]]**This article or section needs expansion.** ​ [[:​title:​file:​tango-view-fullscreen|{{:​images:​3:​38:​tango-view-fullscreen.png?​nolink&​48x48|Tango-view-fullscreen.png}}]] +
- +
-**Reason:​** ​ How to do this if you [[:​title:​openssh#​force_public_key_authentication|force public key authentication]]?​ (Discuss in [[https://​wiki.archlinux.org/​title/​Talk:​SSH_keys|Talk:​SSH keys]]) +
- +
-Once you have generated a key pair, you will need to copy the public key to the remote server so that it will use SSH key authentication. The public key file shares the same name as the private key except that it is appended with a ''​.pub'' ​ extension. Note that the private key is not shared and remains on the local machine. +
- +
-==== Simple method ==== +
- +
-**Note:​** ​ This method might fail if the remote server uses a non-''​sh'' ​ shell such as ''​tcsh'' ​ as default and uses OpenSSH older than 6.6.1p1. See [[https://​bugzilla.redhat.com/​show_bug.cgi?​id=1045191|this bug report]]. +
- +
-If your key file is ''​~/​.ssh/​id_rsa.pub'' ​ you can simply enter the following command.<​code>​ +
-$ ssh-copy-id remote-server.org +
-</​code>​ +
- +
-If your username differs on remote machine, be sure to prepend the username followed by ''​@'' ​ to the server name. +
- +
-<​code>​ +
-$ ssh-copy-id username@remote-server.org +
-</​code>​ +
- +
-If your public key filename is anything other than the default of ''​~/​.ssh/​id_rsa.pub'' ​ you will get an error stating ''/​usr/​bin/​ssh-copy-id:​ ERROR: No identities found''​. In this case, you must explicitly provide the location of the public key. +
- +
-<​code>​ +
-$ ssh-copy-id -i ~/​.ssh/​id_ed25519.pub username@remote-server.org +
-</​code>​ +
- +
-If the ssh server is listening on a port other than default of 22, be sure to include it within the host argument. +
- +
-<​code>​ +
-$ ssh-copy-id -i ~/​.ssh/​id_ed25519.pub -p 221 username@remote-server.org +
-</​code>​ +
- +
-==== Manual method ==== +
- +
-By default, for OpenSSH, the public key needs to be concatenated with ''​~/​.ssh/​authorized_keys''​. Begin by copying the public key to the remote server. +
- +
-<​code>​ +
-$ scp ~/​.ssh/​id_ecdsa.pub username@remote-server.org:​ +
-</​code>​ +
- +
-The above example copies the public key (''​id_ecdsa.pub''​) to your home directory on the remote server via ''​scp''​. Do not forget to include the '':'' ​ at the end of the server address. Also note that the name of your public key may differ from the example given. +
- +
-On the remote server, you will need to create the ''​~/​.ssh'' ​ directory if it does not yet exist and append your public key to the ''​authorized_keys'' ​ file. +
- +
-<​code>​ +
-$ ssh username@remote-server.org +
-username@remote-server.org'​s password: +
-$ mkdir ~/.ssh +
-$ chmod 700 ~/.ssh +
-$ cat ~/​id_ecdsa.pub>>​ ~/​.ssh/​authorized_keys +
-$ rm ~/​id_ecdsa.pub +
-$ chmod 600 ~/​.ssh/​authorized_keys +
-</​code>​ +
- +
-The last two commands remove the public key file from the server and set the permissions on the ''​authorized_keys'' ​ file such that it is only readable and writable by you, the owner. +
- +
-===== SSH agents ===== +
- +
-If your private key is encrypted with a passphrase, this passphrase must be entered every time you attempt to connect to an SSH server using public-key authentication. Each individual invocation of ''​ssh'' ​ or ''​scp'' ​ will need the passphrase in order to decrypt your private key before authentication can proceed. +
- +
-An SSH agent is a program which caches your decrypted private keys and provides them to SSH client programs on your behalf. In this arrangement,​ you must only provide your passphrase once, when adding your private key to the agent'​s cache. This facility can be of great convenience when making frequent SSH connections. +
- +
-An agent is typically configured to run automatically upon login and persist for the duration of your login session. A variety of agents, front-ends, and configurations exist to achieve this effect. This section provides an overview of a number of different solutions which can be adapted to meet your specific needs. +
- +
-==== ssh-agent ==== +
- +
-''​ssh-agent'' ​ is the default agent included with OpenSSH. It can be used directly or serve as the back-end to a few of the front-end solutions mentioned later in this section. When ''​ssh-agent'' ​ is run, it forks to background and prints necessary environment variables. E.g. +
- +
-<​code>​ +
-$ ssh-agent +
-</​code>​ +
- +
-<​code>​ +
-SSH_AUTH_SOCK=/​tmp/​ssh-vEGjCM2147/​agent.2147;​ export SSH_AUTH_SOCK;​ +
-SSH_AGENT_PID=2148;​ export SSH_AGENT_PID;​ +
-echo Agent pid 2148; +
-</​code>​ +
- +
-To make use of these variables, run the command through the ''​eval'' ​ command. +
- +
-<​code>​ +
-$ eval $(ssh-agent) +
-</​code>​ +
- +
-<​code>​ +
-Agent pid 2157 +
-</​code>​ +
- +
-Once ''​ssh-agent'' ​ is running, you will need to add your private key to its cache: +
- +
-<​code>​ +
-$ ssh-add ~/​.ssh/​id_ed25519 +
-</​code>​ +
- +
-<​code>​ +
-Enter passphrase for /​home/​user/​.ssh/​id_ed25519:​ +
-Identity added: /​home/​user/​.ssh/​id_ed25519 (/​home/​user/​.ssh/​id_ed25519) +
-</​code>​ +
- +
-If your private key is encrypted, ''​ssh-add'' ​ will prompt you to enter your passphrase. Once your private key has been successfully added to the agent you will be able to make SSH connections without having to enter your passphrase. +
- +
-**Tip:​** ​ To make all ''​ssh'' ​ clients, including ''​git'' ​ store keys in the agent on first use, add the configuration setting ''​AddKeysToAgent yes'' ​ to ''​~/​.ssh/​config''​. Other possible values are ''​confirm'',​ ''​ask'' ​ and ''​no'' ​ (default). +
- +
-In order to start the agent automatically and make sure that only one ''​ssh-agent'' ​ process runs at a time, add the following to your ''​~/​.bashrc'':​ +
- +
-<​code>​ +
-if ! pgrep -u "​$USER"​ ssh-agent>​ /dev/null; then +
-    ssh-agent -t 1h> "​$XDG_RUNTIME_DIR/​ssh-agent.env"​ +
-fi +
-if [[ ! "​$SSH_AUTH_SOCK"​ |]]; then +
-    source "​$XDG_RUNTIME_DIR/​ssh-agent.env">/​dev/​null +
-fi +
-</​code>​ +
- +
-This will run a ''​ssh-agent'' ​ process if there is not one already, and save the output thereof. If there is one running already, we retrieve the cached ''​ssh-agent'' ​ output and evaluate it which will set the necessary environment variables. The lifetime of the unlocked keys is set to 1 hour. +
- +
-There also exist a number of front-ends to ''​ssh-agent'' ​ and alternative agents described later in this section which avoid this problem. +
- +
-=== Start ssh-agent with systemd user === +
- +
-It is possible to use the [[:​title:​systemd:​user|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.<​code>​ +
-~/​.config/​systemd/​user/​ssh-agent.service +
-</​code>​ +
- +
-<​code>​ +
-[Unit] +
-Description=SSH key agent +
- +
-[Service] +
-Type=simple +
-Environment=SSH_AUTH_SOCK=%t/​ssh-agent.socket +
-# DISPLAY required for ssh-askpass to work +
-Environment=DISPLAY=:​0 +
-ExecStart=/​usr/​bin/​ssh-agent -D -a $SSH_AUTH_SOCK +
- +
-[Install] +
-WantedBy=default.target +
-</​code>​ +
- +
-Then //​export// ​ the [[:​title:​environment_variable|environment variable]] ''​SSH_AUTH_SOCK="​$XDG_RUNTIME_DIR/​ssh-agent.socket"'' ​ in your [[:​title:​login_shell|login shell]] initialization file, such as ''​~/​.bash_profile'' ​ or ''​~/​.zprofile''​. +
- +
-Finally, [[:​title:​enable|]] or [[:​title:​start|title]] the service with the ''​–user'' ​ flag. +
- +
-**Note:** +
- +
-  * If you use GNOME, this environment variable is overridden by default. See [[:​title:​gnome:​keyring#​disable_keyring_daemon_components|GNOME/​Keyring#​Disable keyring daemon components]]. +
-  * Make sure to not overwrite an existing ''​SSH_AUTH_SOCK'' ​ if you want to be able to use a [[:​title:​openssh#​agent_forwarding|forwarded ssh agent]]. +
- +
-**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. +
- +
-=== ssh-agent as a wrapper program === +
- +
-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 ''​startx'' ​ command, you can instead prefix it with ''​ssh-agent'' ​ like so:<​code>​ +
-$ ssh-agent startx +
-</​code>​ +
- +
-And so you do not even need to think about it you can put an alias in your ''​.bash_aliases'' ​ file or equivalent:​ +
- +
-<​code>​ +
-alias startx='​ssh-agent startx'​ +
-</​code>​ +
- +
-Doing it this way avoids the problem of having extraneous ''​ssh-agent'' ​ instances floating around between login sessions. Exactly one instance will live and die with the entire X session. +
- +
-**Note:​** ​ As an alternative to calling ''​ssh-agent startx'',​ you can add ''​eval $(ssh-agent)'' ​ to ''​~/​.xinitrc''​. +
- +
-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. +
- +
-==== GnuPG Agent ==== +
- +
-The [[:​title:​gnupg#​gpg-agent|gpg-agent]] has OpenSSH Agent protocol emulation. See [[:​title:​gnupg#​ssh_agent|GnuPG#​SSH agent]] for necessary configuration. +
- +
-==== Keychain ==== +
- +
-[[https://​www.funtoo.org/​Keychain|Keychain]] is a program designed to help you easily manage your SSH keys with minimal user interaction. It is implemented as a shell script which drives both //​ssh-agent// ​ and //​ssh-add//​. A notable feature of Keychain is that it can maintain a single //​ssh-agent// ​ process across multiple login sessions. This means that you only need to enter your passphrase once each time your local machine is booted. +
- +
-=== Installation === +
- +
-[[:​title:​install|Install]] the [[https://​archlinux.org/​packages/?​name=keychain|keychain]] package. +
- +
-=== Configuration === +
- +
-**Warning:​** ​ As of 2015-09-26, the ''​-Q,​ –quick'' ​ option has the unexpected side-effect of making //​keychain// ​ switch to a newly-spawned //​ssh-agent// ​ upon relogin (at least on systems using [[:​title:​gnome|GNOME]]),​ forcing you to re-add all the previously registered keys. +
- +
-Add a line similar to the following to your [[:​title:​shell|]] configuration file, //​e.g.// ​ if using [[:​title:​bash|Bash]]:<​code>​ +
-~/.bashrc +
-</​code>​ +
- +
-<​code>​ +
-eval $(keychain --eval --quiet id_ed25519 id_rsa ~/​.keys/​my_custom_key) +
-</​code>​ +
- +
-**Note:​** ​ ''​~/​.bashrc'' ​ is used instead of the upstream suggested ''​~/​.bash_profile'' ​ because on Arch it is sourced by both login and non-login shells, making it suitable for textual and graphical environments alike. See [[:​title:​bash#​invocation|Bash#​Invocation]] for more information on the difference between those. +
- +
-In the above example, +
- +
-  * the ''​–eval'' ​ switch outputs lines to be evaluated by the opening ''​eval'' ​ command; this sets the necessary environment variables for an SSH client to be able to find your agent. +
-  * ''​–quiet'' ​ will limit output to warnings, errors, and user prompts. +
-Multiple keys can be specified on the command line, as shown in the example. By default keychain will look for key pairs in the ''​~/​.ssh/'' ​ directory, but absolute path can be used for keys in non-standard location. You may also use the ''​–confhost'' ​ option to inform keychain to look in ''​~/​.ssh/​config'' ​ for ''​IdentityFile'' ​ settings defined for particular hosts, and use these paths to locate keys. +
- +
-See ''​keychain –help'' ​ or [[https://​man.archlinux.org/​man/​keychain.1|keychain(1)]] for details on setting //​keychain// ​ for other shells. +
- +
-To test Keychain, simply open a new terminal emulator or log out and back in your session. It should prompt you for the passphrase of the specified private key(s) (if applicable),​ either using the program set in ''​$SSH_ASKPASS'' ​ or on the terminal. +
- +
-Because Keychain reuses the same //​ssh-agent// ​ process on successive logins, you should not have to enter your passphrase the next time you log in or open a new terminal. You will only be prompted for your passphrase once each time the machine is rebooted. +
- +
-=== Tips === +
- +
-  * //​keychain// ​ expects public key files to exist in the same directory as their private counterparts,​ with a ''​.pub'' ​ extension. If the private key is a symlink, the public key can be found alongside the symlink or in the same directory as the symlink target (this capability requires the ''​readlink'' ​ command to be available on the system). +
-  * to disable the graphical prompt and always enter your passphrase on the terminal, use the ''​–nogui'' ​ option. This allows to copy-paste long passphrases from a password manager for example. +
- +
-  * if you do not want to be immediately prompted for unlocking the keys but rather wait until they are needed, use the ''​–noask'' ​ option. +
- +
-**Note:​** ​ Keychain is able to manage [[:​title:​gpg|GPG]] keys in the same fashion. By default it attempts to start //​ssh-agent// ​ only, but you can modify this behavior using the ''​–agents'' ​ option, //​e.g.// ​ ''​–agents ssh,​gpg''​. See [[https://​man.archlinux.org/​man/​keychain.1|keychain(1)]]. +
- +
-==== x11-ssh-askpass ==== +
- +
-The [[https://​archlinux.org/​packages/?​name=x11-ssh-askpass|x11-ssh-askpass]] package provides a graphical dialog for entering your passhrase when running an X session. //​x11-ssh-askpass// ​ depends only on the [[https://​archlinux.org/​packages/?​name=libx11|libx11]] and [[https://​archlinux.org/​packages/?​name=libxt|libxt]] libraries, and the appearance of //​x11-ssh-askpass// ​ is customizable. While it can be invoked by the //​ssh-add// ​ program, which will then load your decrypted keys into [[#​ssh-agent|ssh-agent]],​ the following instructions will, instead, configure //​x11-ssh-askpass// ​ to be invoked by the aforementioned [[#​keychain|Keychain]] script. +
- +
-Install the [[https://​archlinux.org/​packages/?​name=keychain|keychain]] and [[https://​archlinux.org/​packages/?​name=x11-ssh-askpass|x11-ssh-askpass]] packages. +
- +
-Edit your ''​~/​.xinitrc'' ​ file to include the following lines, replacing the name and location of your private key if necessary. Be sure to place these commands **before** ​ the line which invokes your window manager.<​code>​ +
-~/​.xinitrc +
-</​code>​ +
- +
-<​code>​ +
-keychain ~/​.ssh/​id_ecdsa +
-[ -f ~/​.keychain/​$HOSTNAME-sh ] && . ~/​.keychain/​$HOSTNAME-sh 2>/​dev/​null +
-[ -f ~/​.keychain/​$HOSTNAME-sh-gpg ] && . ~/​.keychain/​$HOSTNAME-sh-gpg 2>/​dev/​null +
-... +
-exec openbox-session +
-</​code>​ +
- +
-In the above example, the first line invokes //​keychain// ​ and passes the name and location of your private key. If this is not the first time //​keychain// ​ was invoked, the following two lines load the contents of ''​$HOSTNAME-sh'' ​ and ''​$HOSTNAME-sh-gpg'',​ if they exist. These files store the environment variables of the previous instance of //​keychain//​. +
- +
-=== Calling x11-ssh-askpass with ssh-add === +
- +
-The //​ssh-add// ​ manual page specifies that, in addition to needing the ''​DISPLAY'' ​ variable defined, you also need ''​SSH_ASKPASS'' ​ set to the name of your askpass program (in this case //​x11-ssh-askpass//​). It bears keeping in mind that the default Arch Linux installation places the //​x11-ssh-askpass// ​ binary in ''/​usr/​lib/​ssh/'',​ which will not be in most people'​s ''​PATH''​. This is a little annoying, not only when declaring the ''​SSH_ASKPASS'' ​ variable, but also when theming. You have to specify the full path everywhere. Both inconveniences can be solved simultaneously by symlinking:​ +
- +
-<​code>​ +
-$ ln -sv /​usr/​lib/​ssh/​x11-ssh-askpass ~/​bin/​ssh-askpass +
-</​code>​ +
- +
-This is assuming that ''​~/​bin'' ​ is in your ''​PATH''​. So now in your ''​.xinitrc'',​ before calling your window manager, one just needs to export the ''​SSH_ASKPASS'' ​ environment variable: +
- +
-<​code>​ +
-$ export SSH_ASKPASS=ssh-askpass +
-</​code>​ +
- +
-and your [[:​title:​x_resources|X resources]] will contain something like:<​code>​ +
-ssh-askpass*background:​ #000000 +
-</​code>​ +
- +
-Doing it this way works well with [[#​ssh-agent_as_a_wrapper_program|the above method on using ]]//​[[#​ssh-agent_as_a_wrapper_program|ssh-agent]]//​ [[#​ssh-agent_as_a_wrapper_program|as a wrapper program]]. You start X with ''​ssh-agent startx'' ​ and then add //​ssh-add// ​ to your window manager'​s list of start-up programs. +
- +
-=== Theming === +
- +
-The appearance of the //​x11-ssh-askpass// ​ dialog can be customized by setting its associated [[:​title:​x_resources|X resources]]. Some examples are the .ad files at [[https://​github.com/​sigmavirus24/​x11-ssh-askpass|https://​github.com/​sigmavirus24/​x11-ssh-askpass]]. See [[https://​man.archlinux.org/​man/​x11-ssh-askpass.1|x11-ssh-askpass(1)]] for full details. +
- +
-=== Alternative passphrase dialogs === +
- +
-There are other passphrase dialog programs which can be used instead of //​x11-ssh-askpass//​. The following list provides some alternative solutions. +
- +
-  * [[https://​archlinux.org/​packages/?​name=ksshaskpass|ksshaskpass]] uses the [[:​title:​kde_wallet|KDE Wallet]]. +
-  * [[https://​archlinux.org/​packages/?​name=openssh-askpass|openssh-askpass]] uses the [[:​title:​qt|Qt]] library. +
-  * [[https://​archlinux.org/​packages/?​name=lxqt-openssh-askpass|lxqt-openssh-askpass]] +
- +
-==== pam_ssh ==== +
- +
-The [[http://​pam-ssh.sourceforge.net/​|pam_ssh]] project exists to provide a [[:​title:​pluggable_authentication_module|Pluggable Authentication Module]] (PAM) for SSH private keys. This module can provide single sign-on behavior for your SSH connections. On login, your SSH private key passphrase can be entered in place of, or in addition to, your traditional system password. Once you have been authenticated,​ the pam_ssh module spawns ssh-agent to store your decrypted private key for the duration of the session. +
- +
-To enable single sign-on behavior at the tty login prompt, install the unofficial [[https://​aur.archlinux.org/​packages/​pam_ssh/​|pam_ssh]]<​sup>​AUR</​sup> ​  ​package. +
- +
-**Note:​** ​ pam_ssh 2.0 now requires that all private keys used in the authentication process be located under ''​~/​.ssh/​login-keys.d/''​. +
- +
-Create a symlink to your private key file and place it in ''​~/​.ssh/​login-keys.d/''​. Replace the ''​id_rsa'' ​ in the example below with the name of your own private key file.<​code>​ +
-$ mkdir ~/​.ssh/​login-keys.d/​ +
-$ cd ~/​.ssh/​login-keys.d/​ +
-$ ln -s ../id_rsa +
-</​code>​ +
- +
-Edit the ''/​etc/​pam.d/​login'' ​ configuration file to include the text highlighted in bold in the example below. The order in which these lines appear is significiant and can affect login behavior. +
- +
-**Warning:​** ​ Misconfiguring PAM can leave the system in a state where all users become locked out. Before making any changes, you should have an understanding of how PAM configuration works as well as a backup means of accessing the PAM configuration files, such as an Arch Live CD, in case you become locked out and need to revert any changes. An IBM developerWorks [[https://​developer.ibm.com/​tutorials/​l-pam/​|article]] is available which explains PAM configuration in further detail.<​code>​ +
-/​etc/​pam.d/​login +
-</​code>​ +
- +
-<​code>​ +
-#%PAM-1.0 +
- +
-auth       ​required ​    ​pam_securetty.so +
-auth       ​requisite ​   pam_nologin.so +
-auth       ​include ​     system-local-login +
-auth       ​optional ​    ​pam_ssh.so ​       try_first_pass +
-account ​   include ​     system-local-login +
-session ​   include ​     system-local-login +
-session ​   optional ​    ​pam_ssh.so +
-</​code>​ +
- +
-In the above example, login authentication initially proceeds as it normally would, with the user being prompted to enter his user password. The additional ''​auth'' ​ authentication rule added to the end of the authentication stack then instructs the pam_ssh module to try to decrypt any private keys found in the ''​~/​.ssh/​login-keys.d'' ​ directory. The ''​try_first_pass'' ​ option is passed to the pam_ssh module, instructing it to first try to decrypt any SSH private keys using the previously entered user password. If the user's private key passphrase and user password are the same, this should succeed and the user will not be prompted to enter the same password twice. In the case where the user's private key passphrase user password differ, the pam_ssh module will prompt the user to enter the SSH passphrase after the user password has been entered. The ''​optional'' ​ control value ensures that users without an SSH private key are still able to log in. In this way, the use of pam_ssh will be transparent to users without an SSH private key. +
- +
-If you use another means of logging in, such as an X11 display manager like [[:​title:​slim|SLiM]] or [[:​title:​xdm|XDM]] and you would like it to provide similar functionality,​ you must edit its associated PAM configuration file in a similar fashion. Packages providing support for PAM typically place a default configuration file in the ''/​etc/​pam.d/'' ​ directory. +
- +
-Further details on how to use pam_ssh and a list of its options can be found in the pam_ssh(8) man page. +
- +
-=== Using a different password to unlock the SSH key === +
- +
-If you want to unlock the SSH keys or not depending on whether you use your key's passphrase or the (different!) login password, you can modify ''/​etc/​pam.d/​system-auth'' ​ to<​code>​ +
-/​etc/​pam.d/​system-auth +
-</​code>​ +
- +
-<​code>​ +
-#%PAM-1.0 +
- +
-auth      [success=1 new_authtok_reqd=1 ignore=ignore default=ignore] ​ pam_unix.so ​    ​try_first_pass nullok +
-auth      required ​ pam_ssh.so ​     use_first_pass +
-auth      optional ​ pam_permit.so +
-auth      required ​ pam_env.so +
- +
-account ​  ​required ​ pam_unix.so +
-account ​  ​optional ​ pam_permit.so +
-account ​  ​required ​ pam_time.so +
- +
-password ​ required ​ pam_unix.so ​    ​try_first_pass nullok sha512 shadow +
-password ​ optional ​ pam_permit.so +
- +
-session ​  ​required ​ pam_limits.so +
-session ​  ​required ​ pam_unix.so +
-session ​  ​optional ​ pam_permit.so +
-session ​  ​optional ​ pam_ssh.so +
-</​code>​ +
- +
-For an explanation,​ see [[https://​unix.stackexchange.com/​a/​239486|[7]]]. +
- +
-=== Known issues with pam_ssh === +
- +
-Work on the pam_ssh project is infrequent and the documentation provided is sparse. You should be aware of some of its limitations which are not mentioned in the package itself. +
- +
-  * Versions of pam_ssh prior to version 2.0 do not support SSH keys employing the newer option of ECDSA (elliptic curve) cryptography. If you are using earlier versions of pam_ssh you must use either RSA or DSA keys. +
- +
-  * The ''​ssh-agent'' ​ process spawned by pam_ssh does not persist between user logins. If you like to keep a [[:​title:​gnu_screen|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. +
- +
-==== pam_exec-ssh ==== +
- +
-As an alternative to [[#​pam_ssh|pam_ssh]] you can use [[https://​aur.archlinux.org/​packages/​pam_exec-ssh/​|pam_exec-ssh]]<​sup>​AUR</​sup> ​  . It is a shell script that uses pam_exec. Help for configuration can be found [[https://​github.com/​x70b1/​pam_exec-ssh|upstream]]. +
- +
-==== GNOME Keyring ==== +
- +
-If you use the [[:​title:​gnome|GNOME]] desktop, the [[:​title:​gnome_keyring|GNOME Keyring]] tool can be used as an SSH agent. See the [[:​title:​gnome_keyring|GNOME Keyring]] article for further details. +
- +
-==== Store SSH keys with Kwallet ==== +
- +
-For instructions on how to use kwallet to store your SSH keys, see [[:​title:​kde_wallet#​using_the_kde_wallet_to_store_ssh_key_passphrases|KDE Wallet#​Using the KDE Wallet to store ssh key passphrases]]. +
- +
-==== KeePass2 with KeeAgent plugin ==== +
- +
-[[https://​lechnology.com/​software/​keeagent/​|KeeAgent]] is a plugin for [[:​title:​keepass|KeePass]] that allows SSH keys stored in a KeePass database to be used for SSH authentication by other programs. +
- +
-  * Supports both PuTTY and OpenSSH private key formats. +
-  * Works with native SSH agent on Linux/Mac and with PuTTY on Windows. +
- +
-See [[:​title:​keepass#​plugin_installation_in_keepass|KeePass#​Plugin installation in KeePass]] or [[:​title:​install|]] the [[https://​archlinux.org/​packages/?​name=keepass-plugin-keeagent|keepass-plugin-keeagent]] package. +
- +
-This agent can be used directly, by matching KeeAgent socket: ''​KeePass → Tools → Options → KeeAgent → Agent mode socket file → %XDG_RUNTIME_DIR%/​keeagent.socket''​- and environment variable: ''​export SSH_AUTH_SOCK="​$XDG_RUNTIME_DIR"<​nowiki>'/</​nowiki>​keeagent.socket'''​. +
- +
-==== KeePassXC ==== +
- +
-The KeePassXC fork of KeePass [[https://​keepassxc.org/​docs/#​faq-ssh-agent-how|supports being used as an SSH agent by default]]. It is also compatible with KeeAgent'​s database format. +
- +
-===== Troubleshooting ===== +
- +
-==== Key ignored by the server ==== +
- +
-  * If it appears that the SSH server is ignoring your keys, ensure that you have the proper permissions set on all relevant files. +
- +
-  * For the local machine:<​code>​ +
-$ chmod 700 ~/.ssh +
-$ chmod 600 ~/​.ssh/​key +
-</​code>​ +
- +
-  * For the remote machine: +
- +
-<​code>​ +
-$ chmod 700 ~/.ssh +
-$ chmod 600 ~/​.ssh/​authorized_keys +
-</​code>​ +
- +
-  * 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): +
- +
-<​code>​ +
-$ chmod go-w /​home/​target_user +
-</​code>​ +
- +
-  * If that does not solve the problem you may try temporarily setting ''​StrictModes'' ​ to ''​no'' ​ in ''/​etc/​ssh/​sshd_config''​. If authentication with ''​StrictModes off'' ​ is successful, it is likely an issue with file permissions persists. +
- +
-  * Make sure keys in ''​~/​.ssh/​authorized_keys'' ​ are entered correctly and only use one single line. +
-  * 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|#​Generating an SSH key pair]]. +
-  * You may want to use debug mode and monitor the output while connecting:<​code>​ +
-# /​usr/​bin/​sshd -d +
-</​code>​ +
- +
-  * If you gave another name to your key, for example ''​id_rsa_server'',​ you need to connect with the ''​-i'' ​ option: +
- +
-<​code>​ +
-$ ssh -i id_rsa_server user@server +
-</​code>​ +
- +
-===== A Solution for Existing Repositories ===== +
- +
-You may encounter the “**Please make sure you have the correct access rights**” error in an existing repository with which you are working. This may be caused by an SSH issue so you should check your SSH authentication setup if you use it before you proceed. +
- +
-[[https://​careerkarma.com/​blog/​git-another-process-seems-to-be-running/​|» MORE: Git Another git process seems to be running in this repository Solution ]] +
- +
-Assuming SSH authentication is not your issue, make sure you are pointing to the correct remote URL in your repository. You can do this using the git remote command: +
- +
-<hljs language-undefined>​ git remote -v </​hljs>​ +
- +
-The -v flag lets us see the URLs to which our repository is pointing: +
- +
-<hljs language-perl>​ origin [[https://​github.com/​career-karma-tutorials/​ck-git|https://​github.com/​career-karma-tutorials/​ck-git]] (fetch) origin [[https://​github.com/​career-karma-tutorials/​ck-git|https://​github.com/​career-karma-tutorials/​ck-git]] (push) </​hljs>​ +
- +
-Suppose our repository moved to ck-git-tutorials and a new repository called ck-git was created over which we have no permission. We’ll have to update our remote pointer so we point to the correct repository. +
- +
-We can do this using the [[https://​careerkarma.com/​blog/​git-change-remote/​|git remote set-url command]]:​ +
- +
-<hljs language-cpp>​ git remote set-url origin [[https://​github.com/​career-karma-tutorials/​ck-git-tutorials|https://​github.com/​career-karma-tutorials/​ck-git-tutorials]] </​hljs>​+
  
-This will change our pointer to the ck-git-tutorials repository. Now, we can change our repository and push our code using the git push command. 
  
  
linux/ssh/key.1635611778.txt.gz · Последние изменения: 2023/01/12 12:16 (внешнее изменение)