Перейти к содержимому

Known hosts для чего

  • автор:

Known hosts для чего

make-ssh-known-hosts [ —initialdns начальный_dns ]
[ —server сервер_доменных_имен ]
[ —subdomains разделенный_запятыми_список_поддоменов ]
[ —debug уровень_отладки ]
[ —timeout время_ожидания_выполнения_ssh ]
[ —pingtimeout время_ожидания_ping ]
[ —passwordtimeout время_ожидания_запроса_пароля ]
[ —notrustdaemon ]
[ —norecursive ]
[ —domainnamesplit ]
[ —silent ]
[ —keyscan ]
[ —nslookup путь_к_программе_nslookup ]
[ —ssh путь_к _программе_ssh ]
имя_домена [ take_regexp [ remove_regexp ]]

ОПИСАНИЕ

make-ssh-known-hosts это сценарий на perl5, который поможет в создании файла /etc/ssh_known_hosts , используемого ssh для хранения ключей всех публично известных машин. Обычно ssh не разрешает вход в систему с использованием аутентификации rhosts или /etc/hosts.equiv, если серверу не известен ключ клиентской машины. В добавок, ключи машин используются для предотвращения атак, построенных по принципу man-in-the-middle.

В дополнение к /etc/ssh_known_hosts ssh также использует файл $HOME/.ssh/known_hosts . Однако, этот файл предназначен для хранения только тех ключей машин, использование которых продиктовано спецификой данных пользователей. Подразумевается, что файл /etc/ssh_known_hosts может обслуживаться и быть периодически дополнен новыми ключами для любой новой машины только системным администратором.

Программа make-ssh-known-hosts найдет все машины в домене послав DNS запрос к главному серверу доменных имен домена. Главный сервер доменных имен будет найден посредством поиска SOA записи для домена с начального сервера имен (который может быть указан при помощи параметра —initialdns . Имя главного сервера доменных имен так-же может быть задано напрямую при помощи параметра —server .

После получения списка имен машин make-ssh-known-hosts пробует получить публичный ключ от каждой машины в домене. Сначала предпринимается попытка установить соединение через порт ssh для проверки, действует компьютер или нет, и если действует, то будет предпринята попытка выполнить на удаленной машине с помощью ssh команду cat /etc/ssh_host_key.pub . Если команда была выполнена удачно, то программа будет знать, что ssh на удаленной машине установлено правильно и затем из результа будет извлечен публичный ключ и вывод /etc/ssh_known_hosts о нем будет направлен в STDOUT. Так как make-ssh-known-hosts обычно выполняется до того как на удаленных машинах будет создана запись в файле /etc/ssh_known_hosts, вам может понадобиться использование RSA-аутентификации для доступа к компьютерам.

Если по каким-то причинам выполнение программы завершилась неудачей, то будет произведена проверка был ли получен ssh клиентом в процессе инициализации публичный ключ с удаленной машины, и если это не так, то будет распечатана правильная запись, а если задан параметр —notrustdaemon , то она будет отмечена символом комментария.

имя_домена — это имя домена для которого был сгенерирован файл. По умолчанию make-ssh-known-hosts извлекает также из домена все суб-домены. Во многих местах заносят некоторые домены в файл /etc/ssh_known_hosts . Записи для каждого домена должны быть извлечены раздельно, запуском make-ssh-known-hosts для каждого домена отдельно. Результаты затем могут быть объединены в одном окончательном файле.

take_regexp — это регулярное выражение perl, которое соответствует именам машин, взятым из домена. Соответствующие данные содержат все записи DNS в формате » имя_поля=значение «. Разделителем полей является новая строка, соответствия perl сделаны многострочными и не чувствительны к регистру. Многострочный режим означает, что вы можете использовать регулярные выражения подобные » ^wks=.*telnet.*$ » для соответствия всем компьютерам имеющим поля WKS (хорошо известные службы) содержащим значение «telnet».

remove_regexp — это схожее выражение, но те машины, которые соответствуют регулярному выражению, не будут добавлены (это может быть использовано, например, для отфильтровывания PC и Mac используя поле hinfo: » ^hinfo=.*(mac|pc) «).

ПАРАМЕТРЫ

—initialdns начальный_dns -i начальный_dns Указывает начальный сервер службы доменных имен, используемый для опроса записей SOA для домена.

—server сервер_доменных_имен -se сервер_доменных_имен Устанавливает главный сервер доменных имен домена. Этот компьютер используется для запроса списка DNS домена.

—subdomains список_суб-доменов -su список_суб-доменов Разделенный запятыми список суб-доменов, которые будут добавлены к именам машин. Например, если списком суб-доменов являются » foo, foo.bar, foo.bar.zappa, foo.bar.zappa.hut.fi «, то когда машина foobar будет добавлена в файл /etc/ssh_known_hosts , то она получит псевдонимы » foobar, foobar.foo, foobar.foo.bar, foobar.foo.bar.zappa, foobar.foo.bar.zappa.hut.fi «. По умолчанию берутся все составляющие имени машины, но второе с конца имени машины является базовым для компьютера. (Последний элемент имени, как правило, используется для обозначения кода государства, и что-нибудь типа foobar.foo.bar.zappa.hut не имело бы смысла.)

—debug уровень_отладки -de уровень_отладки Устанавливает уровень отладки. Значением по умолчанию является 5, большие значения дадут более информативный вывод. Использование большого значения (такого как 999) будет выводить уйму отладочной информации.

—timeout время_ожидания_выполнения_ssh -ti время_ожидания_выполнения_ssh Время ожидания выполнения команды ssh . Значением по умолчанию является 60 секунд.

—pingtimeout время_ожидания_ping -pi время_ожидания_ping Время ожидания пока выполняется ping портов ssh. Значением по умолчанию является 3 секунды.

—passwordtimeout время_ожидания_запроса_пароля -pa время_ожидания_запроса_пароля Время ожидания запроса пароля для команды ssh. По умолчанию пароль не будет востребован. Используйте значение 0 для отмены ожидания запроса пароля.

—notrustdaemon -notr
Если команда ssh дала сбой используйте публичный ключ сохраненный в локальном файле известных машин и надейтесь, что это правильный ключ для машины. Если этот параметр не задан, такие записи будут закомментированы в сгенерированном файле /etc/ssh_known_hosts .

—norecursive -nor
Сообщает make-ssh-known-hosts , что он должен только извлечь ключи для заданного домена без рекурсии.

—domainnamesplit -do
Разбить имя домена для получения списка поддоменов. Используйте этот параметр, если вы не желаете, чтобы имена машин были разбиты автоматически. По умолчанию разбивка производится по принципу машина за машиной. Если доменом является zappa.hut.fi и имя машины foo.bar, то по умолчанию будут добавлены записи » foo, foo.bar, foo.bar.zappa, foo.bar.zappa.hut.fi » Использование этого параметра добавит записи » foo.bar, foo.bar.zappa, foo.bar.zappa.hut.fi «.

—silent -si
Быть тихим.

—keyscan -k
Вывод списка всех компьютеров в формате «ipaddr1,ipaddr2. ipaddrn, имя_машины.домен.co,имя_машины,ipaddr1,ipaddr2, все_остальные_записи_имен_машин». Вывод этого может быть скормлен в ssh-keyscan для получения ключей.

—nslookup путь_к_программе_nslookup -n путь_к_программе_nslookup Указывает путь к программе nslookup .

—ssh путь_к_программе_ssh -ss путь_к_программе_ssh Указывает путь, включая все параметры, к программе ssh .

ПРИМЕРЫ

Команда make-ssh-known-hosts cs.hut.fi > /etc/ssh_known_hosts

найдет все публичные ключи в домене cs.hut.fi и поместит из в файл /etc/ssh_known_hosts с разбивкой доменных имен по-машинно.

Команда make-ssh-known-hosts hut.fi ‘^wks=.*ssh’ > hut-hosts

найдет все машины в домене hut.fi и его под-доменах, имеющих свой собственный сервер имен (cs.hut.fi , tf.hut.fi , tky.hut.fi ), которые имеют службу ssh, и поместит их публичные ключи в файл hut-hosts. Для этого требуется, чтобы сервер доменных имен hut.fi определял бы все машины с действующими службами ssh по их WKS-записям. Если никто ещё не добавил ssh в WKS, то лучше использовать команду make-ssh-known-hosts hut.fi ‘^wks=.*telnet’ > hut-hosts

которая отобрала бы машины, имеющие сервис telnet. Это использует список субдоменов по умолчанию.

Команда make-ssh-known-hosts hut.fi ‘dipoli.hut.fi ‘ ‘^hinfo=.*(mac|pc)’ > dipoli-hosts

найдет все машины в домене hut.fi , которые находятся в поддомене dipoli.hut.fi (обратите внимание, что dipoli.hut.fi не имеет собственного сервера имен, так что записи о нем находятся на сервере hut.fi ) и что они не являются Mac или PC.

ФАЙЛЫ

/etc/ssh_known_hosts — глобальный список публичных ключей машин.

СМОТРИ ТАКЖЕ

ssh (1), sshd (8), ssh-keygen (1), ping (8), nslookup (8), perl (1), perlre (1)

АВТОРЫ

Tero Kivinen Александр Блохин — перевод на русский язык.

ЛИЦЕНЗИОННОЕ СОГЛАШЕНИЕ

Это свободная программа; вы можете повторно распространять и/или модифицировать make-ssh-known-hosts в соответствии с Универсальной Общественной Лицензией GNU, опубликованной Фондом Свободного ПО; либо версии 2, либо (по вашему выбору) любой более поздней версии.
Make-ssh-known-hosts распространяется в надежде, что она будет полезной, но БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ; даже без подразумеваемых гарантий КОММЕРЧЕСКОЙ ЦЕННОСТИ или ПРИГОДНОСТИ ДЛЯ КОНКРЕТНОЙ ЦЕЛИ. Для получения подробных сведений смотрите Универсальную Общественную Лицензию GNU.
Вы должны были получить копию Универсальной Общественной Лицензии GNU вместе с этой программой; если нет, напишите по адресу: Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
———————————————————————-

Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.

Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.

Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be included in translations approved by the the author instead of in the original English. ———————————————————————-

Что записано в файле .ssh/known_hosts

Каждый раз, когда мы подключаемся по протоколу ssh к серверу, ssh клиент проверяет совпадает ли публичный ключ для этого сервера с тем, который был прошлый раз (по крайней мере так рекомендует делать стандарт ssh). В OpenSSH список известных ключей серверов хранится в файле known_hosts. Под катом коротко о том, что и как конкретно там хранится.

Все эксперименты проводились на Linux (Debian/Mint/Ubuntu). За расположение и содержание файлов в других ОС не ручаюсь.

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

The authenticity of host ‘192.168.0.2 (192.168.0.2)’ can’t be established.
RSA key fingerprint is SHA256:kd9mRkEGLo+RBBNpxKp7mInocF3/Yl/0fXRsGJ2JfYg.
Are you sure you want to continue connecting (yes/no)?

Если согласиться, то в файл ~/.ssh/known_hosts добавится такая строка:

|1|CuXixZ+EWfgz40wpkMugPHPalyk=|KNoVhur7z5NAZmNndtwWq0kN1SQ= ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCeiF4OOOUhWvOYrh/e4q91+iz+i9S0s3M2LPq+GAhRlhKt5vKyEVd6x6m26cc98Y+SQXnCB9GWeVYk8jlFHEXnY4YWeWLDwXIhHBJYt5yz3j5Wkg95x+mPvO9FLSBk/Al2GbH5q6F+hZIlLmO6ciISmX4TtcG1sw4SwoTADrrhdM0OJd+c5CU8iqCbc6PznYbLZXCvqPZTWeSbTLUcUu1Ti+7xGwT8DF+tIyLFcU+zxd0QnwJIbNvewkHs0LsMOWFVPz/Nd0XiVXimX+ugCDBZ/4q8NUwH9SGzCMAvnnr+D1I8X2vhSuRsTsQXL5P3vf8elDxPdDrMJzNtlBCbLWzV

Тут через пробел записаны три элемента: хэш от имени сервера, название используемого ассиметричного алгоритма и публичный ключ сервера. Разберём их по очереди.

А если почитать инструкцию

  • в начале строки может находиться пометка «@cert-authority» или “@revoked”, означающие, соответственно, что в этой строке записан публичный ключ ЦА или что этот ключ был отозван и не может быть использован.
  • в конце строки может быть произвольный комментарий
Имя сервера

В примере хэш от имени сервера (хоста) выглядит так:

|1|CuXixZ+EWfgz40wpkMugPHPalyk=|KNoVhur7z5NAZmNndtwWq0kN1SQ=

На самом деле тут может быть записано и имя хоста в открытом виде или маска, задающая множество допустимых имён. Но у меня по умолчанию сохраняется хэшированое имя. Запись разделена на 3 части символом «|». Первая часть — алгоритм хэширования. «1» соответствует HMAC-SHA1 (других не видел). Вторая часть — соль (ключ для HMAC). Третья часть — собственно хэш (вывод HMAC).

Проверяем

from base64 import b64decode import hmac salt = b64decode("CuXixZ+EWfgz40wpkMugPHPalyk https://tools.ietf.org/html/rfc4253">RFC-4253 перечислены 4 ассиметричных алгоритма: ssh-dss (по стандарту обязательный, но считается слабым и начиная с OpenSSH7.0 выключен по-умолчанию), ssh-rsa (рекомендуемый), pgp-sign-rsa (опциональный), pgp-sign-dss (опциональный). По умолчанию в Linux генерируются ключи первых двух видов и для не упомянутых в RFC алгоритмов на эллиптических кривых. Предпочтение отдаётся последним, однако клиент может выбрать алгоритм опцией HostKeyAlgorithms. 

Как проверить нужный (не по-умолчанию) отпечаток ключа
Это может быть полезно если, например, при первом заходе на сервер вы хотите проверить отпечаток ключа, а знаете только отпечаток ключа ssh-rsa. Тогда можно подключиться такой командой:
ssh root@192.168.0.2 -o HostKeyAlgorithms=ssh-rsa

Если нужно задать ещё и алгоритм хэширования ключа, то можно использовать опцию FingerprintHash. Например, если известен только md5 от ssh-rsa можно подключиться так:
ssh root@192.168.0.2 -o HostKeyAlgorithms=ssh-rsa -o FingerprintHash=md5


Публичный ключ

Публичный ключ в known_hosts совпадает с тем, который записан в файле /etc/ssh/ssh_host_rsa_key.pub на сервере (вместо rsa подставить название используемого алгоритма). Если снять Base64 кодирование, то внутри будет ещё раз название алгоритма и собственно компоненты ключа.

А чего бы и не снять Base64
b'\x00\x00\x00\x07ssh-rsa\x00\x00\x00\x03\x01\x00\x01\x00\x00\x01\x01\x00\x9e\x88^\x0e8\xe5!Z\xf3\x98\xae\x1f\xde\xe2\xafu\xfa,\xfe\x8b\xd4\xb4\xb3s6,\xfa\xbe\x18\x08Q\x96\x12\xad\xe6\xf2\xb2\x11Wz\xc7\xa9\xb6\xe9\xc7=\xf1\x8f\x92Ay\xc2\x07\xd1\x96yV$\xf29E\x1cE\xe7c\x86\x16yb\xc3\xc1r!\x1c\x12X\xb7\x9c\xb3\xde>V\x92\x0fy\xc7\xe9\x8f\xbc\xefE- d\xfc\tv\x19\xb1\xf9\xab\xa1~\x85\x92%.c\xbar"\x12\x99~\x13\xb5\xc1\xb5\xb3\x0e\x12\xc2\x84\xc0\x0e\xba\xe1t\xcd\x0e%\xdf\x9c\xe4%

Видно, что идут 4 байта, в которые записана длина поля, потом само поле и т.д. Первое поле — название алгоритма, остальные зависят от конкретного алгоритма. В приведённом выше ключе 3 поля:

b'ssh-rsa' - название b'\x01\x00\x01' - публичная экспонента b'\x00\x9e\x88^\x0e8\xe5!Z\xf3\x98\xae\x1f\xde\xe2\xafu\xfa,\xfe\x8b\xd4\xb4\xb3s6,\xfa\xbe\x18\x08Q\x96\x12\xad\xe6\xf2\xb2\x11Wz\xc7\xa9\xb6\xe9\xc7=\xf1\x8f\x92Ay\xc2\x07\xd1\x96yV$\xf29E\x1cE\xe7c\x86\x16yb\xc3\xc1r!\x1c\x12X\xb7\x9c\xb3\xde>V\x92\x0fy\xc7\xe9\x8f\xbc\xefE- d\xfc\tv\x19\xb1\xf9\xab\xa1~\x85\x92%.c\xbar"\x12\x99~\x13\xb5\xc1\xb5\xb3\x0e\x12\xc2\x84\xc0\x0e\xba\xe1t\xcd\x0e%\xdf\x9c\xe4%
Отпечаток ключа (Fingerprint)

Отпечаток ключа, который предлагается сверить при первом подключении — это соответствующий хэш (в примере — SHA256) от публичного ключа из прошлого пункта и из /etc/ssh/ssh_host_rsa_key.pub, закодированный в base64 для хэш функций семейства SHA или в hex для MD5.

Считаем

from hashlib import sha256 from base64 import b64decode, b64encode pub_key_bin = b64decode("AAAAB3NzaC1yc2EAAAADAQABAAABAQCeiF4OOOUhWvOYrh/e4q91+iz+i9S0s3M2LPq+GAhRlhKt5vKyEVd6x6m26cc98Y+SQXnCB9GWeVYk8jlFHEXnY4YWeWLDwXIhHBJYt5yz3j5Wkg95x+mPvO9FLSBk/Al2GbH5q6F+hZIlLmO6ciISmX4TtcG1sw4SwoTADrrhdM0OJd+c5CU8iqCbc6PznYbLZXCvqPZTWeSbTLUcUu1Ti+7xGwT8DF+tIyLFcU+zxd0QnwJIbNvewkHs0LsMOWFVPz/Nd0XiVXimX+ugCDBZ/4q8NUwH9SGzCMAvnnr+D1I8X2vhSuRsTsQXL5P3vf8elDxPdDrMJzNtlBCbLWzV") hash = sha256(pub_key_bin).digest() fingerprint = b64encode(hash) print(fingerprint) > b'kd9mRkEGLo+RBBNpxKp7mInocF3/Yl/0fXRsGJ2JfYg=' 
  • Информационная безопасность
  • Криптография
  • Сетевые технологии

Everything You Important You Should Know About the known_hosts file in Linux

There is a known_hosts file in the .ssh directory and it is an integral part of the SSH mechanism. Learn more about it.

Everything You Important You Should Know About the known_hosts file in Linux

If you look into the .ssh folder in your home directory, you'll see a known_hosts file among other files.

abhishek@LHB:~$ ls -l .ssh total 16 -rwxr-xr-x 1 abhishek abhishek 618 Aug 30 16:52 config -rw------- 1 abhishek abhishek 1766 Nov 12 2017 id_rsa -rw-r--r-- 1 abhishek abhishek 398 Nov 12 2017 id_rsa.pub -rw------- 1 abhishek abhishek 1 Sep 26 15:00 known_hosts

Here, id_rsa is your private SSH key, id_rsa.pub is the public SSH key. The config file in SSH is used for creating profiles to connect easily to various hosts. It is not a common file and I have created it specifically.

The focus of this article is on the last file, known_hosts . This ~/.ssh/known_hosts file is a vital part of client SSH configuration files.

Let me share more details on it.

What is the known_hosts file in SSH?

The known_hosts file stores the public keys of the hosts accessed by a user. This is a very important file that assures that the user is connecting to a legitimate server by saving its identity to your local system. It also helps in avoiding the man-in-the-middle attacks.

When you connect to a new remote server via SSH, you are prompted whether you want to add the remote hosts to known_hosts file.

SSH known_hosts file

The message basically asked if you wanted to add the details of the remote system to your system.

The authenticity of host '194.195.118.85 (194.195.118.85)' can't be established. ED25519 key fingerprint is SHA256:wF2qILJg7VbqEE4/zWmyMTSwy3ja7be1jTIg3WzmpeE. This key is not known by any other names Are you sure you want to continue connecting (yes/no/[fingerprint])?

If you go with yes, the identity of the server is saved to your system.

Avoiding man in the middle attack

Man in the middle attack illustration

Imagine that you connect to a server regularly and have added it to the known_hosts file.

If there is a change in the public key of the remote server, your system will note this change thanks to the information stored in the known_hosts file. You'll be alerted immediately about this change:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: POSSIBLE DNS SPOOFING DETECTED! @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ The RSA host key for xyz remote host has changed,and the key for the corresponding IP address xxx.yy.xxx.yy is unknown. This could either mean that DNS SPOOFING is happening or the IP address for the host and its host key have changed at the same time. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the-middle attack)! It is also possible that the RSA host key has just been changed. The fingerprint for the RSA key sent by the remote host is 69:4e:bb:70:6a:64:e3:78:07:6f:b4:00:41:07:d8:9c. Please contact your system administrator. Add correct host key in /home/.ssh/known_hosts to get rid of this message. Offending key in /home/.ssh/known_hosts:1 Keyboard-interactive authentication is disabled to avoid man-in-the-middle attacks.

In such a case, you can contact the remote server’s administrator prior to accepting this new key. In this way, you can ensure that the remote server or host has not been compromised.

Sometimes a server’s or host’s key is intentionally altered either by the administrator or due to re-installation of the server.

Whatever be the reason for this change, you will need to first delete the old key from the known_hosts file for reconnecting to the remote server. Next time when you connect to this server, the client host will create a new host key for this server.

Managing Multiple Authenticated Users

As mentioned earlier, once a client host successfully connects to a remote server, its known_hosts file is appended with the server’s public key.

Sometimes you want a server to be authenticated to multiple users without being prompted for server key verification. For example, you are running some sort of configuration management tool like Ansible and you don’t want the client host to ask for server key verification.

So, If you have multiple users, you can bypass the SSH interactive prompt using three ways:

  • Manually appending the public key of the server to the known_hosts file of each user.
  • Use a command-line option -o StrictHostKeyChecking=no with each client while accessing the server over SSH (not recommended)
  • Register all your hosts in a master or primary ssh_known_hosts file and then orchestrate this file to all the client hosts. Also, to make this work, the ssh-keyscan command can be used:
ssh-keyscan -H -t rsa ‘your-server-ip’ >> /etc/ssh/ssh_known_hosts

The below screenshot shows how to use the StrictHostKeyChecking=no option:

Bypassing Host Key Checking using the StrictHostKeyChecking=no switch

The first method of managing multiple users for authenticating a server is the most toilsome as compared to the other two.

Getting remote system details from the known_hosts file

This is not an easy and straightforward task.

Almost all Linux systems set HashKnownHosts parameter to Yes in the SSH config file. It is a security feature.

This means that the details in the known_hosts file are hashed. You can see random numbers but cannot make anything out of them.

abhishek@LHB:~$ cat .ssh/known_hosts |1|yWIW17YIg0wBRXJ8Ktt4mcfBqsk=|cFHOrZ8VEx0vdOjau2XQr/K7B/c= ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFR293PJnDCj59XxfqYGctrMo60ZU5IOjACZZNRp9D6f |1|Ta7hoH/az4O3l2dwfaKh8O2jitI=|WGU5TKhMA+2og1qMKE6kmynFNYo= ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCmrxLW436AyBGyGCggl/j2qBCr782AVIvbiTEsWNBWLcWMKYAQpTdAXnaV4bBRqnk2NJg/60XDHKC2DF1tzx6ABWN/R6vcUAbulI9H1RUWpJ1AiDmFL84MvW2UukbpN5a6Lr+DvjclVqPxJRjQKr6Vy2K9oJgGKnHVcWSIHeAlW49kCCg5fIxF8stBTqJg0cRk6uxmcYVud1vh9a7SaZGK+jFZTB75RiHAVFuitHWpljecMxJRNYy/EhmmXrrvyU8pObVXlWlDd61uwExi4uEwNSY+Do7vR1y8svnt9mjTzzyM6MhT4sOcxWmNgdmw7bU/wPpie3dSjZMQeu2mQCSM7SG28dwjSyFPpanRsZKzkh0okAaCSItoNwl6zOf6dE3zt0s5EI6BPolhFAbT3NqmXRblxb7eV8rGEPf14iguHUkg6ZQr2OUdfeN1FYNMJ8Gb9RD159Mwjl4/jPIBdnXvt7zYct3XhPKm7Wxv4K/RWZE837C7mGQh2KEahWajdq8= |1|NonAy25kVXL24U2mx6ZNxAY5m98=|ypf0IMpf3qq3vhrvUMprssOhODs= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBE3br/9jaZfdB+qBxiVEZBJMb4XQONwzV4tH1xeFZX/zkyws2eBHrVO9O5l9b6M6+gO6nBtCwAzzaeLOn6mo8GQ= 

You can get the related entries from the known_hosts if you know the hostname or the IP address of the system:

ssh-keygen -l -F

But if you want a single command that could list all the servers and their details in clear text, that's not possible.

There are specially crafted tools and scripts used for deciphering the known_hosts but that's not in the scope for a regular user like you and me.

Remove an entry from the known_hosts

If you want to remove a specific entry from the known_hosts file, you can do so if you know the hostname or IP of the remote system.

ssh-keygen -R server-hostname-or-IP

This is much better than identifying the entries related to a server and then manually removing them using the rm command.

Conclusion

You have a better hold of system security with proper knowledge of various SSH configuration files. ‘Known_hosts’ is a vital part of these files.

I have only covered the known_hosts file here; if you’d like to explore more about SSH, look at our Getting Started With SSH in Linux guide.

Understanding SSH known_hosts File with Examples

The ssh known_hosts file is a file that stores the public key of all of the servers that you have connected using ssh.

This file is used to verify the identity of servers in the future. Ssh can automatically add keys to this file, but they can be added manually as well.

In this article, I will share everything about the SSH know_hosts file.

Table of Contents

What is SSH known_hosts file?

In the context of computer networking, known_hosts is a file used by SSH (Secure Shell) clients to verify the identity of a remote server before establishing a connection.

When an SSH client connects to a server for the first time, the server’s public key is exchanged with the client and saved in the known_hosts file on the client’s system.

On subsequent connections, the client verifies the server’s identity by checking the key in the known_hosts file against the one presented by the server.

If there is a match, the connection will proceed. If the match fails, ssh will fail with an error message.

If there is no key at all listed for that remote host, then the key’s fingerprint will be displayed and there will be the option to automatically add the key to the file.

This file can be created and edited manually, but if it does not exist it will be created automatically by ssh when it first connects to a remote host.

The known host file is stored in /etc/ssh/known_hosts or in .ssh/known_hosts in each user’s home directory.

Format of known_hosts file in SSH

The format is one public key or certificate per unbroken line. Each line contains a hostname, number of bits, exponent, and modulus. At the beginning of the line is either the hostname or a hash representing the hostname.

It is possible to use a comma-separated list of hosts in the hostname field if a host has multiple names or if the same key is used on multiple machines in a server pool.

SSH known_hosts Example

Here is one example of host key with IP:

10.254.171.53 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItb
POVVQF/CzuAeQNv4fZVf2pLxpGHle15zkpxOosckequUDxoq

SSH known_hosts file permissions

  • $HOME/.ssh folder should have permission 700.
  • config and private/secret key files id_rsa_XXX should have 600.
  • known_hosts and public/shared key files id_rsa_XXX.public should have 644.

Add public key to known_hosts manually

We can use ssh-keygen with -F option to search known_hosts file. $ ssh-keygen -F server3.example.com . The default file to be searched will be ~/.ssh/known_hosts and the key is printed if found.

A different file can be searched using the -f option. If a key must be removed from the file, the -R option works similarly to search by host and then remove it if found even if the host name is hashed.

$ ssh-keygen -R server4.example.com -f ~/.ssh/known_hosts

When a key is removed, it will then be appended to the file ~/.ssh/known_hosts.old in case it is needed later. If a non-default file is used with either -F or -R then the name including the path must be specified using -f. But -f is optional if the default file is intended.

How to view the ssh known_hosts file?

To view the ssh know_hosts file on your Linux system, you can use the following command:

cat ~/.ssh/known_hosts
or
vi ~/.ssh/known_hosts

To add a new host to the ssh know_hosts file, you can use the following command:

$ ssh-keyscan -t rsa [remote.server.com] >> ~/.ssh/known_hosts
$ ssh-keyscan -H remote.server.com >> ~/.ssh/known_hosts

To remove a host from the know hosts file, you can use the following command:

$ ssh-keygen -R [remote.server.com]
$ ssh-keygen -r [remote.server.com]

Where should I store my ssh known_hosts file?

The ssh known_hosts file should be stored in the ~/.ssh directory. For example, the full path to the ssh know_hosts file is: ~/.ssh/known_hosts

What are some common problems with the ssh known_hosts file?

The ssh know_hosts file is a file that stores information about hosts that you have connected to using ssh. This file can help to prevent man-in-the-middle attacks by verifying the host key before connecting.

A common problem with the ssh know_hosts file is when you try to connect to a host and get an error message: “WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!”

This usually happens if you changed out hardware on the server that you are connecting to, or if there was some other change in settings on the remote server.

If you get this error message, you can fix it by removing the host from your ssh know_hosts file and adding it back again:

$ ssh-keygen -R [remote.server.com]
$ ssh-keyscan -t rsa [remote.server.com] >> ~/.ssh/known_hosts
$ ssh-keyscan -H remote.server.com >> ~/.ssh/known_hosts

Another common problem with the ssh know_hosts file is when you try to connect to a host and get an error message: “WARNING: POSSIBLE DNS SPOOFING DETECTED!” .

This usually happens when you try to connect to a host that does not exist.

If you get this error message, then check your /etc/hosts file and make sure that the name of the remote server is there and it has a valid IP address assigned to it.

Posted on Last updated: March 2, 2023

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *