Linux ssh agent install

Use ssh agent to hold your keys¶

Remembering your credentials and which key you use for different services can become non-trivial if you work with many remote systems. You can use the ssh config file, ~/.ssh/config to specify features of your connection e.g. if you have different usernames on different systems:

Host service IdentityFile id_ed25519_service User userid_service

Enabling the SSH Agent¶

So far we have just replaced the need to enter a password to access a remote host with the need to enter a key pair passphrase. Because of this is may be tempting to leave the passphrase empty when creating your key so that we do not have to enter it every time we access a service which may be many times a day. This is poor security practise and is likely to be in breach of the acceptable use policies covering the services you are accessing.

It is also a completely unnecessary risk as you can enable an agent on your local system so that you only have to enter the passphrase once and after that you will be able to access the remote system without entering the passphrase. Here we will demostrate how to use ssh-agent but:

  • on Linux you might want to consider the GNOME keyring
  • if using putty you can use pageant
  • if using MobaXterm you can use its internal MobAgent

Start ssh-agent

Most modern Linux distributions (and macOS) should have ssh-agent running by default. If your system does not then you should find the instructions for enabling it in your distribution using Google. Typically you can check this with:

If the output is empty then it isn’t running. It can be launched with:

eval `ssh-agent` Agent pid 123 

and now you can confirm it is running with:

Adding your key to the agent¶

To add the private part of your key pair to the SSH Agent, use the ssh-add command (on your local machine).

By default this will add the files: ~/.ssh/id_rsa , ~/.ssh/id_dsa , ~/.ssh/id_ecdsa , ~/ssh/id_ed25519 and ~/.ssh/identity , if they exist.

If we want to add a specific key that is not one of these we must specify it explicitly:

ssh-add ~/.ssh/id_ed25519-service Enter passphrase for home/user/.ssh/id_ed25519_service: [Passphrase] Identity added: home/user/.ssh/id_ed25519_service (home/user/.ssh/id_ed25519_service) 

We can also add keys for a specific length of time. To add the key for one hour we inculde the flag and parameter -t 3600 , you will need to enter your passphrase one more time:

ssh-add -t 3600 ~/.ssh/id_ed25519-service Enter passphrase for home/user/.ssh/id_ed25519_service: [Passphrase] Identity added: home/user/.ssh/id_ed25519_service (home/user/.ssh/id_ed25519_service) Lifetime set to 3600 seconds

Now you can test that you can access the remote host without needing to enter your passphrase:

ssh [userID]@ 'date' Wed May 8 10:42:56 BST 2020 

again we have run date on the remote service to confirm that we have been able to use the ssh-agent successfully.

Читайте также:  Linux directory start process

Remember that in the above user will be your username on your local machine and that [userID] is you username on the remote .

Add your key to the agent

Linux:¶

Following the instructions above add just the key you have created to access the remote service to your agent.

Windows:¶

Using pageant which is included with the putty bundle, add your ssh-key, text instructions are in the documentation.

Agent lifetime

By default ssh-agent will store your key forever, until the machine is rebooted. Remember that we are trying to ensure that we operate as securely as possible. If we could be completely confident that our local machine could not be taken and compromised then we would not use passwords.

Similarly with the ssh-agent we must consider how long that the passphrase needs to be or should be remembered. If we are in a secure office at work and we will be accessing the service repeatedly throughout the day then we might want the key to be remembered for several hours. If we are doing half an hour’s work in a cafe we would probably want to have the keys stored for that length of time. Note that the time is in seconds.

At the end of a session you can remove all stored keys with:

Источник

как настроить ssh-agent

Есть множество способов настроить ssh-agent в Linux. Приведу самый удобный для себя, который нашел относительно недавно.

Для начала, напишу зачем нужен ssh-agent. Представим, что у вас есть несколько ssh ключей, каждый ключ защищен паролем (да, лучше запароливать ключи). Вы решаете соединиться с каким-то сервером и при каждом соединении ssh клиент просит ввести пароль. Неудобно, не так ли?

А что, если вы хотите соединиться с несколькими серверами по цепочке или же скачать какой-то приватный git репозиторий на удаленном сервере? Придется загружать туда свой приватный ssh ключ. Опять неудобно.

Вот тут на выручку и приходит ssh-agent, он же агент ssh. Он безопасно хранит в памяти все ваши ключи, не требует пароль постоянно, и его можно пробрасывать на удаленные сервера без особых усилий (ssh -A).

Как же включить и настроить его?

Для начала убедитесь, что он установлен в системе (на примере Debian-based систем), скорей всего он уже установлен:

sudo apt-get update sudo apt-get -y install openssh-client 

ssh-agent идет в комплекте с ssh клиентом, удобно.

Далее пропишите в ~/.profile следующую строку:

Почему в ~/.profile ? Потому что нам достаточно запустить агент всего лишь единожды для сессии, можно конечно запускать их на каждый bash процесс и т.п., но это излишне.

Читайте также:  Linux command for copy file

Что значит эта команда? Она запустит ssh-agent, который выдаст необходимые переменные окружения для shell, которые будут экспортированы во все shell процессы пользователя.

Проверить эти переменные можно вот так:

 └─$ env | grep SSH_ SSH_AUTH_SOCK=/tmp/ssh-Hg0DgkE9cvLu/agent.2346 SSH_AGENT_PID=2347 

Мы запустили ssh-agent, но этого еще недостаточно, он ничего не знает про наши ssh ключи. Добавим же их в него. Для этого отредактируем ~/.ssh/config , если у вас его нет, то создайте. Вот сокращенный пример моего конфига:

Host * ForwardAgent yes AddKeysToAgent yes IdentityFile ~/.ssh/id_ecdsa IdentityFile ~/.ssh/id_rsa 

Первой строкой мы указываем к каким хостам применять данную конфигурацию, как видно, ко всем.

Далее мы разрешаем проброс агента на удаленные сервера. Это не всегда безопасно, поэтому можете отключить эту опцию.

AddKeysToAgent yes самая главная строка, она добавляет ключи в агент, если ключ запаролен, то при любом первом подключении у вас будет запрошен пароль и далее сохранен на протяжении всей сессии.

Строки с IdentityFile указывают нужные мне ключи для использования клиентом ssh.

Вот и всё, для вступления изменений в силу достаточно в терминале выполнить . ~/.profile и попробовать подключиться к любому серверу по ssh, например:

Для проверки добавленных ключей в агент, выполните

 └─$ ssh-add -l 256 SHA256:EdQaJRIu22tco6giujxrZhsVH44Io+8gkhfUjfj3lNI insider@localhost (ECDSA) 2048 SHA256:9wUbS3ZM8dHsmcRWc3ZBAeQqzN8kw+78grWFSEyL9To (RSA) 256 SHA256:Upg/EVhSYoErKdFBVvhKt50dxLJeZtUewn6bpGfQnnE insider@xps13 (ED25519) 

Источник

ssh-agent: How to configure ssh-agent, agent forwarding, & agent protocol

Request demo

The ssh-agent is a helper program that keeps track of users’ identity keys and their passphrases . The agent can then use the keys to log into other servers without having the user type in a password or passphrase again. This implements a form of single sign-on (SSO).

The SSH agent is used for SSH public key authentication . It uses SSH keys for authentication. Users can create SSH keys using the ssh-keygen command and install them on servers using the ssh-copy-id command.

Contents

Starting ssh-agent

On most Linux systems, ssh-agent is automatically configured and run at login, and no additional actions are required to use it. However, an SSH key must still be created for the user.

If ssh-agent is not automatically started at login, it can be started manually with the command

The ssh-agent command outputs commands to set certain environment variables in the shell. The commands output by default are compatible with /bin/sh and /bin/bash . To output commands for the C-shell ( /bin/csh or /bin/tcsh ), add -c .

The easiest way to check is to check the value of the SSH_AGENT_SOCK environment variable. If it is set, then the agent is presumably running. It can be checked by

Also, to allow key-based logins to servers, public key authentication must be enabled on the server. In OpenSSH it is enabled by default. It is controlled by the PubkeyAuthentication option in sshd_config .

Adding SSH keys to the Agent

By default, the agent uses SSH keys stored in the .ssh directory under the user’s home directory. The ssh-add command is used for adding identities to the agent. In the simplest form, just run if without argument to add the default files ~/.ssh/id_rsa , .ssh/id_dsa , ~/.ssh/id_ecdsa , ~/.ssh/id_ed25519 , and ~/.ssh/identity . Otherwise, give it the name of the private key file to add as an argument.

Читайте также:  Linux свой вариант загрузки

The following command will list private keys currently accessible to the agent:

SSH Agent Forwarding

Furthermore, the SSH protocol implements agent forwarding, a mechanism whereby an SSH client allows an SSH server to use the local ssh-agent on the server the user logs into, as if it was local there. When the user uses an SSH client on the server, the client will try to contact the agent implemented by the server, and the server then forwards the request to the client that originally contacted the server, which further forwards it to the local agent. This way, ssh-agent and agent forwarding implement single sign-on that can progress transitively.

A wonderful feature of the single sign-on provided by SSH is that it works independent of organizational boundaries and geography. You can easily implement single sign-on to servers on the other side of the world, in cloud services, or at customer premises. No central coordination is needed.

To use agent forwarding, the ForwardAgent option must be set to yes on the client (see ssh_config ) and the AllowAgentForwarding option must be set to yes on the server (see sshd_config ).

New call-to-action

Running ssh-agent

The ssh-agent command is usually run from initialization scripts at login, such as from /etc/X11/Xsession.d/90×11-common_ssh-agent on Linux Mint LMDE. Alternatively, any user can configure it to be run from, e.g., the user’s ~/.xsession file or ~/.profile .

The agent outputs environment variable settings that this puts in place. The SSH_AUTH_SOCK environment variable is set to point to a unix-domain socket used for communicating with the agent, and the SSH_AGENT_PID environment variable is set to the process ID of the agent. To get the environment variables set in the user’s shell environment, the agent is usually run with something like the following:

The ssh-agent command accepts the following options:

-a bind_address

Forces to bind the Unix domain socket to the given file path, instead of the default socket.

Forces generation of C-shell commands on stdout. By default the shell is automatically detected.

-E fingerprint_hash Specifies which algorithm to use for generating SSH key fingerprints. Valid values include md5 and sha256 .

Kills the currently running agent.

Forces generation of Bourne shell ( /bin/sh ) commands on stdout. By default the shell is automatically detected.

Specifies a maximum number of seconds that identities are kept in the agent. The value is in seconds, but can be suffixed by m for minutes, h for hours, d for days, and w for weeks. Without this option, the agent keeps the keys in its memory as long as it runs. This can be overridden when running the ssh-add command.

Further Reading

Источник

Оцените статью
Adblock
detector