What is ssh agent in linux

What is ssh agent in linux

If you work a lot on linux and use ssh often, you quickly realize that typing your password every time you connect to a remote host gets annoying.

Not only that, it is not the best solution in terms of security either:

  • Every time you type a password, a snooper has an extra chance to see it.
  • Every host you ssh to with which you use your password, well, has to know your password. Or a hash of your password. In any case, you probably have typed your password on that host once or twice in your life (even if just for passwd, for example).
  • If you are victim of a Man In The Middle attack, your password may get stolen. Sure, you can verify the fingerprint of every host you connect to, and disable authentication without challenge and response in your ssh config. But what if there was a way you didn’t have to do that?

This is where key authentication comes into play: instead of using a password to log in a remote host, you can use a pair of keys, and well, ssh-agent .

Using ssh keys

All you have to do is:

generate a pair of keys with ssh-keygen . This will create two files: a public key (normally .pub), and a private key. The private key is normally kept encrypted on disk. After all, it’s well, supposed to be private. ssh-keygen will ask you to insert a password. Note that this password will be used to decrypt this file from your local disk, and never sent to anyone. And again, as the name suggest, you should never ever disclose your private key.

copy your public key into any system you need to have access to. You can use rsync , scp , type it manually, or well, use the tool provided with openssh: ssh-copy-id . Note that you could even publish your public key online: there is no (known) way to go from a public key to your private key and to get access to any of your systems. And if there was a way, well, public key encryption would be dead, and your bank account likely empty.

and . done! That’s it, really, just try it out:

So. what are the advantages of using keys? There are many:

  1. Your passphrase never leaves your local machine. Which generally makes it harder to steal.
  2. You don’t have a password to remember for each different host. Or.
  3. . you don’t have the same password for all hosts you connect to (depending on your password management philosophies).
  4. If somebody steals your passphrase, there’s not much he can do without your private key.
  5. If you fear somebody has seen your passphrase, you can change it easily. Once. And for all.
  6. If there is a «man in the middle», he may be able to hijack your session. Once (and well, feast on your machine, but that’s another story). If a «man in the middle» got hold of your password instead, he could enjoy your machine later, more stealthy, for longer, and may be able to use your password on other machines.
  7. They just work. Transparently, most of the times. With git , rsync , scp , and all their friends.
  8. You can use an agent to make your life happier and easier.

And if you’re wondering what an agent is, you can go to the next section.

Your agent friend

Ok. So you have read this much of the article, and still we have not solved the problem of having to type your password every freaking time, have we?

That’s where an agent comes in handy. Think of it as a safe box you have to start in the background that holds your keys, ready to be used.

You start an ssh-agent by running something like:

in your shell. You can then feed it keys, with ssh-add like:

or, if your key is in the default location, you can just:

ssh-add will ask your passphrase, and store your private key into the ssh-agent you started earlier. ssh , and all its friends (including git , rsync , scp . ) will just magically use your agent friend when you try to ssh somewhere. Convenient, isn’t it?

Assuming you added all the keys you need, you can now ssh to any host, as many times as you like, without ever ever having to retype your password.

Читайте также:  Windows 10 новых уведомлений нет выкл

Not only that, but you can exploit agent forwarding to jump from one host to another seamlessly.

Let me give you an example:

  • Let’s say you have to connect to a server at your office.
  • Let’s say this server is firewalled. In order to ssh there, you first need to ssh into another gateway . Sounds familiar, doesn’t it? This means you end up doing:

On this second ssh, what happens? Well, if you type your password, your cleartext password is visible to the gateway. Yes, it is sent encrypted, decrypted, and then through the console driver fed to the ssh process. If a keylogger was running, your password would be lost.

Worst: we are back to our original problem, we have to type our password multiple times!

We could, of course, store our private key on the company gateway and run an agent there. But that would not be a good idea, would it? Remember: your private key never leaves your private computer, you don’t want to store it on a remote server.

So, here’s a fancy feature of ssh and ssh-agent : agent forwarding.

On many linux systems, it is enabled by default: but if you pass -A to the first ssh command (or the second, or the third, . ), ssh will ensure that your agent running on your local machine is usable from the remote machine as well.

The second ssh here, run from the company gateway, will not ask you for a password. Instead, it will detect the presence of a remote agent, and use your private key instead, and ask for no password.

Sounds dangerous? Well, there are some risks associated with it, which we’ll discuss in another article. But here is the beauty of the agent:

Your private key never leaves your local computer. That’s right. By design, the agent never ever discloses your private key, it never ever hands it over to a remote ssh or similar. Instead, ssh is designed such as when an agent is detected, the information that needs to be encrypted or verified through the agent is forwarded to the agent. That’s why it is called agent forwarding , and that’s why it is considered a safer option.

Configuring all of this on your machine

So, let’s summarize the steps:

  1. Generate a set of keys, with ssh-keygen .
  2. Install your keys on remote servers, with ssh-copy-id .
  3. Start an ssh-agent to use on your machine, with eval ssh-agent .
  4. ssh-add your key, type your password once.
  5. Profit! You can now ssh to any host that has your public key without having to enter a password, and use ssh -A to forward your agent.

Easy, isn’t it? Where people generally have problems is on how and where to start the ssh-agent , and when and how to start ssh-add .

The long running advice has been to start ssh-agent from your .bashrc, and run ssh-add similarly.

In today’s world, most distributions (including Debian and derivatives), just start an ssh-agent when you first login. So, you really don’t have anything to do, except run ssh-add when you need your keys loaded, and be done with it.

Still many people have snippets to the extent of:

in their .bashrc , which basically says «is there an ssh-agent already running? no? start one, and add my keys».

This is still very annoying: for each console or each session you login into, you end up with a new ssh-agent . Worse: this agent will run forever with your private keys loaded! Even long after you logged out. Nothing and nobody will ever kill your agent.

So, your three lines of .bashrc snippet soon becomes 10 lines (to cache agents on disk), then it breaks the first time you use NFS or any other technology to share your home directory, and then. more lines to load only some keys, some magic in .bash_logout to kill your agent, and your 4 lines of simple .bashrc get out of control

Conclusion

I promised myself to talk about the pitfalls of using an agent and common approaches to solving the most common problems in a dedicated article. My suggestion for now?

Use the ssh-agent tied with your session, and managed by your distro, when one is available (just try ssh-add and see if it works!).

Use -t to ssh-add and ssh-agent , so your private key is kept in the agent for a limited amount of time. One hour? 5 miutes? you pick. But at the end of that time, your key is gone.

For full disclosure, I wrote ssh-ident . Surprisingly, that still doesn’t prevent me from liking it.

Источник

How to use ssh-agent for authentication on Linux / Unix

Table of contents

Using ssh-agent command for non-interactive authentication

Open the terminal and type the following command:
$ eval $(ssh-agent)
$ eval `ssh-agent`
You will see the PID of the ssh-agent as follows on screen:

Use ssh-add to add the private key passphrase to ssh-agent

Now our ssh-agent is running, and you need to provide the passphrase for your ssh private keys. For example, run the ssh-add command:
$ ssh-add
Type the passphrase:

By default it adds the files

/.ssh/id_ed25519_sk. But, we state another private key file as follows:
$ ssh-add

Setting up a maximum lifetime for identities/private keys

Pass the -t life to the ssh-add command to s a maximum lifetime when adding identities to an agent. The lifetime may be specified in seconds or in a time format specified in sshd_config file:
$ ssh-add -t 1800 # 1800 seconds
$ ssh-add -t 45m # 45 minutes
$ ssh-add -t 3h42 # 3 hours 42 minutes
Remember, you can configure GNOME/KDE or macOS desktop to run ssh-agent and unlock keys automatically when log-in. For example:

Use ssh-agent for ssh/sftp/scp command authentication

Once you add the private key (or keys) to the ssh-agent, all you have to do is use ssh, sftp, scp, and all other ssh commands. For instance, I will execute the ssh command for my FreeBSD backup server:
$ ssh user@server
$ ssh user@hostname_or_ip
$ scp file.doc vivek@server1.cyberciti.biz:

/Documents/
# State the private key for public key authentication #
$ ssh -i

/.ssh/aws-web-servers ec2-user@rhel8-web-server
$ ssh -i

/.ssh/linode-nixcraft-servers vivek@1.2.3.4
$ ssh vivek@192.168.2.236

The ssh-agent for non-interactive ssh authentication in action on my Ubuntu Linux desktop

How to list my private keys cached by ssh-agent

Run the following command to lists fingerprints of all identities/private keys:
$ ssh-add -l

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Want to see list all public key parameters of all identities:
$ ssh-add -L

Deleting all cached ssh-agent private keys

Pass the -D option to the ssh-add command:
$ ssh-add -D
You will see confirmation as follows on screen:

Conclusion

In this quick tutorial, you learned how to use ssh-agent for authentication and list/clear out private keys from memory when needed under Linux or Unix-like systems. For further information, see OpenSSH documentation or use the man command to read man pages:
$ man ssh-agent
$ man ssh-add
$ man ssh
$ man sftp
$ man scp
$ man sshd_config

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Про SSH Agent

Введение

SSH-agent является частью OpenSSH. В этом посте я объясню, что такое агент, как его использовать и как он работает, чтобы сохранить ваши ключи в безопасности. Я также опишу переадресацию агента и то, как она работает. Я помогу вам снизить риск при использовании переадресации агента и поделюсь альтернативой переадресации агента, которую вы можете использовать при доступе к своим внутренним хостам через bastion’ы.

Что такое SSH-agent

ssh-agent — это менеджер ключей для SSH. Он хранит ваши ключи и сертификаты в памяти, незашифрованные и готовые к использованию ssh . Это избавляет вас от необходимости вводить пароль каждый раз, когда вы подключаетесь к серверу. Он работает в фоновом режиме в вашей системе, отдельно от ssh , и обычно запускается при первом запуске ssh .

Агент SSH хранит секретные ключи в безопасности из-за того, что он не делает:

  • Он не записывает никакой информации о ключах на диск.
  • Он не позволяет экспортировать ваши личные ключи.

Секретные ключи, хранящиеся в Агенте, могут использоваться только для одной цели: подписания сообщения.

Но если агент может только подписывать сообщения, как SSH шифрует и расшифровывает трафик?

При первом изучении открытых и закрытых ключей SSH естественно предположить, что SSH использует эти пары ключей для шифрования и дешифрования трафика. Именно так я и думал. Но это не тот случай. Пара ключей SSH используется только для аутентификации во время первоначального соединения.

Например, вот как проверяется ключ пользователя во время SSH-соединения, с точки зрения сервера:

  • Клиент предоставляет серверу публичный ключ.
  • Сервер генерирует и отправляет короткое случайное сообщение, прося клиента подписать его с помощью приватного ключа.
  • Клиент просит агента SSH подписать сообщение и пересылает результат обратно на сервер.
  • Сервер проверяет подпись, используя публичный ключ клиента.
  • Теперь у сервера есть доказательство того, что клиент владеет приватным ключом.

Позже в процессе соединения генерируется набор новых, эфемерных и симметричных ключей, которые используются для шифрования трафика сеанса SSH. Эти ключи могут даже не длиться весь сеанс; событие «rekey» происходит через регулярные промежутки времени.

Протокол агента

SSH использует сокет домена Unix для общения с агентом по протоколу SSH agent. Большинство людей используют ssh-agent , который поставляется с OpenSSH, но есть множество альтернатив с открытым исходным кодом.

Протокол агента настолько прост, что можно было бы написать базовый SSH-agent за день или два. Он имеет только несколько основных операций:

  • Добавить обычную пару ключей (публичный и расшифрованный приватный ключи)
  • Добавить ограниченную пару ключей (публичный и расшифрованный приватный ключи)
  • Добавить ключ (обычный или ограниченный) из смарт-карты (только публичный ключ)
  • Удалить ключ
  • Вывод списка ключей, хранящихся в агенте
  • Подпись сообщения ключом, хранящимся в агенте
  • Блокировка или разблокировка всего агента с помощью пароля

Что такое ограниченный ключ? Обычно это ключ, который либо имеет ограниченный срок службы, либо требует явного подтверждения пользователя при его использовании.

Команда ssh-add — это ваш шлюз к агенту SSH. Он выполняет все эти операции, кроме подписи. Когда вы запускаете ssh-add без каких-либо параметров, он будет сканировать ваш домашний каталог на наличие некоторых стандартных ключей и добавлять их в ваш агент. По умолчанию он ищет:

/.ssh/id_ecdsa

Как только вы добавите ключи к связке ключей, они будут автоматически использоваться ssh .

ssh-агент и macOS Keychain
ssh-agent , поставляемый вместе с macOS, может хранить парольную фразу для ключей в macOS Keychain, что делает еще более простым повторное добавление ключей к агенту после перезагрузки. В зависимости от настроек Keychain вам все равно может потребоваться разблокировать его после перезагрузки. Чтобы сохранить ключевые парольные фразы в Keychain, выполните команду ssh-add -K [имя файла ключа] . Парольные фразы обычно хранятся в «Local Items». ssh-agent будет использовать эти сохраненные парольные фразы автоматически по мере необходимости.

Что такое переадресация агента

Функция переадресации агента позволяет вашему локальному агенту SSH связаться через существующее SSH-соединение и прозрачно аутентифицироваться на более удаленном сервере. Например, предположим, что вы входите по SSH в инстанс EC2 и хотите клонировать оттуда приватный репозиторий GitHub. Без переадресации агента вам придется хранить копию вашего приватного ключа GitHub на хосте EC2. При переадресации агента SSH-клиент на EC2 может использовать ключи на вашем локальном компьютере для аутентификации на GitHub.

Как работает переадресация агента

Во-первых, немного предыстории. SSH-соединения могут иметь несколько каналов. Вот распространенный пример: интерактивное соединение с bastion-host (jump box) выполняется на одном канале. Когда для соединения включена переадресация агента (обычно с использованием ssh -A ), в фоновом режиме открывается второй канал для переадресации любых запросов агента обратно на ваш локальный компьютер.

С точки зрения ssh , нет никакой разницы между удаленным и локальным ssh-agent . SSH всегда смотрит на переменную окружения $SSH_AUTH_SOCK , чтобы найти доменный сокет Unix для агента. При подключении к удаленному хосту с включенной переадресацией агента SSHD создаст удаленный доменный сокет Unix, связанный с каналом переадресации агента, и экспортирует $SSH_AUTH_SOCK , указывающий на него.

Переадресация агента связана с определенным риском

Когда вы переадресовываете доменный сокет ssh-agent Unix на удаленный хост, это создает угрозу безопасности: любой человек с root доступом на удаленном хосте может незаметно получить доступ к вашему локальному SSH-agent’y через сокет. Они могут использовать ваши ключи, чтобы выдавать себя за вас на других машинах в сети.

Вот пример того, как это может выглядеть:

Как снизить свой риск при переадресации агента

Вот несколько способов сделать переадресацию агента более безопасной:

  • Не включайте ForwardAgent по умолчанию.

Заблокируйте свой ssh-агент, когда вы используете переадресацию агента. ssh-add -x блокирует агент паролем, а ssh-add -X разблокирует его. Когда вы подключены к удаленному хосту с переадресацией агента, никто не сможет проникнуть в ваш агент без пароля.

Или используйте альтернативный агент SSH, который запрашивает вас, когда он используется. Sekey использует Touch ID на macOS для хранения ключей в анклаве безопасности MacBook Pro.

Или вообще не используйте переадресацию агента. Если вы пытаетесь получить доступ к внутренним хостам через bastion, ProxyJump — гораздо более безопасная альтернатива для этого варианта использования. (смотреть ниже)

Используйте ProxyJump : более безопасная альтернатива

Когда вы хотите пройти через bastion-host (jumpbox), вам действительно не нужна переадресация agent’a. Лучший подход — использовать директиву ProxyJump .

Вместо того чтобы перенаправлять agent’a по отдельному каналу, ProxyJump перенаправляет стандартный вход и выход вашего локального SSH-клиента через bastion и далее на удаленный хост. Вот как это работает:

  1. Запустите ssh -J bastion.example.com cloud.computer.internal для подключения к cloud.computer.internal через ваш bastion хост — bastion.example.com . cloud.computer.internal — это имя хоста, которое можно найти с помощью поиска DNS на bastion.example.com .
  2. Ваш SSH клиент использует ключи от вашего агента для подключения к bastion.example.com .
  3. После подключения SSHD к bastion подключается к cloud.computer.internal и передает это соединение вашему локальному SSH-клиенту.
  4. Ваш локальный SSH-клиент снова проходит через соединение, на этот раз с cloud.computer.internal

Вы можете думать об этом как о SSH в сеансе SSH; за исключением того, что ssh никогда не запускается на bastion. Вместо этого sshd подключается к cloud.computer.internal и дает контроль над этим соединением (стандартный вход и выход) обратно в ваш локальный SSH, который затем выполняет второе соединение.

Скажем bastion-host это bastion.example.com . Я могу настроить свой

Затем я просто запускаю ssh cloud.computer.internal для подключения к внутреннему назначению через bastion — без переадресации агента.

Если ProxyJump не работает…

Более старые версии SSH и SSHD (до версии 7.2, выпущенной в 2016 году) не поддерживают ProxyJump . Но вы можете выполнить эквивалентную операцию, используя ProxyCommand и netcat. Вот вам пример:

Магия здесь заключается в том, что SSH сам по себе является прокси-сервером, который вы используете для SSH. Часть nc %h %p просто открывает необработанное соединение сокета к cloud.computer.internal на порте 22. Стандартный ввод-вывод родительской команды ssh передается прямо в ProxyCommand , чтобы родительский ssh мог аутентифицироваться на внутреннем хосте через прокси-соединение.


Узнайте подробности, как получить востребованную профессию с нуля или Level Up по навыкам и зарплате, пройдя онлайн-курсы SkillFactory:

Источник

Читайте также:  Мыльный шрифт windows 10
Оцените статью
Tutorial requirements
Requirements Linux, macOS, *BSD and Unix-like
Root privileges No
Difficulty Easy
Est. reading time 5m