Ssh host key verification failed как исправить

Whenever we connect to a server via SSH, that server's public key is stored in our home directory. The file is called known_hosts.When we reconnect to the same server, the SSH connection will verify the current public key matches the one we have saved in our known_hosts file.If the server's key has changed since the last time we connected to it, we will receive host key verification failed error (or one similar to it).

If you’ve ever tried to connect to a remote server using ssh, and received an error message that says “Host key verification failed,” you know how frustrating it can be. This article will show you three ways to fix the problem.

What is a Host Key in SSH?

A Host key is a unique identifier that is used to verify the identity of a remote host. When you connect to a remote host, the Host key is verified against a list of known Host keys. If there is a match, the connection will be allowed to proceed. If there is not a match, the connection will be denied.

The Host key is also used to generate a cryptographic signature for each connection. This signature is used to verify the integrity of the data that is transferred between the client and server.

Understanding error message Host key verification failed

If you receive the error message “Host key verification failed”, it means that the key stored for the host you’re trying to connect to has changed. It is often caused by connecting to a different server than the one you originally connected to (for example, your server has been rebuilt by a new one).

Whenever we connect to a server via SSH, that server’s public key is stored in our home directory. The file is called known_hosts. 

This file is local to the user account and contains the known keys for remote hosts. These are collected from the hosts when connecting for the first time.

As with those keys stored in the file, ~/.ssh/known_hosts, these keys are used to verify the identity of the remote host, thus protecting against impersonation or man-in-the-middle attacks.

When we reconnect to the same server, the SSH connection will verify the current public key matches the one we have saved in our known_hosts file. If there is a match, the connection will proceed. If the match fails, ssh will fail with an error message Host key verification failed happens.

Example of Host key verification failed

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 a host key has just been changed. The fingerprint for the RSA key sent by the remote host is x. Please contact your system administrator.
Add correct host key in /home/ec2-user/.ssh/known_hosts to get rid of this message.

Offending RSA key in /home/ec2-user.ssh/known_hosts:222 RSA host key for www.howtouselinux.com has changed and you have requested strict checking.Host key verification failed.

Methods to fix problem of Host key verification failed

Host key verification failed error occurs when the server’s host key does not match the key that was expected. This can happen when the server’s key has been changed, or when the key has been compromised. 

Here are three ways to fix this Host key verification failed error.

  • Manually edit the “~/.ssh/known_hosts” file and remove the old key for the host you’re trying to connect to. This will allow you to connect to the new server without any problems.
  • Use the “ssh-keygen -R” command to remove the old key from your “~/.ssh/known_hosts” file. This will allow you to connect to the new server without any problems.
  • Use the “-o StrictHostKeyChecking=no” option when connecting to the server. This will prevent ssh from checking the “~/.ssh/known_hosts” file, and will allow you to connect to the new server without any problems.

Remove old host key info from known_hosts file

The easiest way to fix the problem of Host key verification failed is removing the old host key info and reconnect the server.

We can fix this issue with the following steps.

  • Locate our known_hosts file
  • open in a general text editor with vi /home/user/.ssh/known_hosts
  • search the old host name and press “ESC dd” to delete the line.
  • save the changes by pressing “esc” and typing “:wq!”.
  • reconnect the server

Remove old host key info with ssh-keygen command

We can also remove the old host key with ssh-keygen command.

Open up a terminal session, and type one of the following

  • ssh-keygen -R hostname
  • ssh-keygen -R ipaddress
  • ssh-keygen -f “/home/ec2-user.ssh/known_hosts” -R “192.168.0.106”

Disable SSH stricthostkeychecking option

The stricthostkeychecking option in SSH is a security feature that verifies the host key information for each connection.

If there is a problem with the host key information, the connection will not be allowed to proceed. This option can be disabled, which will allow the connection to proceed even if there is a problem with the host key information.

  • Open up a terminal window.
  • Type in the following command: ssh -o StrictHostKeyChecking=no hostname

This command removes the old host key for the device in the known_hosts file and replaces old host key with the new host key.

Understanding SSH known_hosts File with Examples

При использовании ssh-сервера вы можете столкнуться с одной из распространенных ошибок: «Host Key Verification Failed». Чтобы понять, почему возникает эта ошибка, давайте сначала разберемся, как ssh устанавливает соединение.

Когда вы пытаетесь подключиться к удаленному серверу, сервер просит вас подтвердить, пытаетесь ли вы установить соединение с правильным сервером.

Если вы наберете «да», клиент добавит открытый ключ хоста в файл «.ssh/known_hosts». После добавления ключа удаленного сервера в следующий раз, когда вы попытаетесь подключиться к тому же серверу, клиент сравнит ключи с ключами, хранящимися в файле «known_hosts».

Вы не получите никаких предупреждений, если ключ присутствует в файле «known_hosts». Сервер будет подключен сразу.

Почему возникает ошибка «Host Key Verification Failed»

Основная причина, вызывающая ошибку Host Key Verification Failed», заключается в том, что ключ удаленного хоста был изменен и больше не тот, который хранится в файле «known_hosts». Ключ обычно меняется, когда серверы перестраиваются, и вы получаете сообщение об ошибке, как показано ниже:

Как исправить ошибку «Host Key Verification Failed»

Чтобы исправить эту ошибку, нам нужно удалить неверный ключ из файла «known_hosts», находящегося в нашей системе в каталоге «.ssh». Ошибка дает вам IP-адрес удаленного сервера и номер строки, в которой хранится ключ в файле «known_hosts».

В приведенной выше ошибки, «/home/user/.ssh/known_hosts:7», то «: 7» является задеть номер строки. Ниже перечислены несколько подходов к исправлению этой ошибки:

Способ 1:

Первый способ исправить эту ошибку – использовать команду sed. Команда «sed» используется для изменения текстовых файлов для поиска, добавления или удаления чего-либо из файлов. Мы используем его для удаления хоста-нарушителя:

$ sed -i '7d' ~.ssh/known_hosts

Если «7» – это номер строки, показанный в приведенной выше ошибке, ваш номер строки может быть другим; убедитесь, что вы используете правильный номер строки. Команда удалит неправильную строку из файла «known_hosts» и решит проблему.

Способ 2:

Второй подход – открыть файл «known_hosts» в любом редакторе:

$ nano.ssh/known_hosts

И вручную удалите оскорбительную строку и сохраните файл.

Способ 3:

Третий метод – удаление сервера с помощью команды «ssh-keygen». Следуйте синтаксису, указанному ниже:

$ ssh-keygen -R [IP_ADDRESS]

Например, чтобы удалить ключ хоста «192.168.10.116», используйте:

$ ssh-keygen -R 192.168.10.116

Заключение

Ошибка проверки ключа хоста возникает, когда ключ удаленного сервера изменяется, а клиент не проверяет его по сохраненным ключам. Ключи сервера хранятся в файле «known_hosts» на стороне клиента, и после установления соединения клиент проверяет ключ, сравнивая его с ключами, хранящимися в файле «known_host», и в случае сбоя вы получаете “Host key verification failed”.

Чтобы исправить это, удалите хост-нарушитель из файла «known_hosts». В этой статье упоминаются три различных метода удаления вредоносного хоста, и любой метод может использоваться для устранения этой ошибки.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

In this article, I am show you how to resolve «host key verification Failed» error in Linux. I am sure many of you uses ssh protocol to access remote host in Linux. Many of you also have observed this «host key verification failed» error while trying to connect remote server through ssh based commands. This error usually occurs when remote host change its key very oftenly due to certain reasons. We will now go through below given 2 different methods to fix this issue.

How to fix SSH "host key verification failed" error in Linux(2 Easy Methods) 1

In this example we have 2 different host to demonstrate the "host key verification failed" error in Linux.

192.168.0.100
192.168.0.106

Here we are trying to copy ssh public key from one host(192.168.0.100) to another host(192.168.0.106) using ssh-copy-id command as you can see below. Like in many ssh error whenever we face this kind of situation then the first thing we always try is to connect remote host through simple ssh command and check if this error still throws or not.

root@localhost:~# ssh-copy-id root@192.168.0.106
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/bin/ssh-copy-id: ERROR: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ERROR: @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
ERROR: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
ERROR: IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
ERROR: Someone could be eavesdropping on you right now (man-in-the-middle attack)!
ERROR: It is also possible that a host key has just been changed.
ERROR: The fingerprint for the ED25519 key sent by the remote host is
ERROR: SHA256:mx1ctmvoleWzmA3kVqOr+H9uIMQFPsK9eTXlnJ5fnGA.
ERROR: Please contact your system administrator.
ERROR: Add correct host key in /root/.ssh/known_hosts to get rid of this message.
ERROR: Offending ECDSA key in /root/.ssh/known_hosts:5
ERROR: remove with:
ERROR: ssh-keygen -f "/root/.ssh/known_hosts" -R "192.168.0.106"
ERROR: ED25519 host key for 192.168.0.106 has changed and you have requested strict checking.
ERROR: Host key verification failed.

NOTE:

Please note that here I am using root user to run all the below commands.You can use any user with sudo access to run all these commands. For more information Please check Step by Step: How to Add User to Sudoers to provide sudo access to the User.

Now here we are trying to connect remote host(192.168.0.106) using ssh command but we see same error here as well.

root@localhost:~# ssh root@192.168.0.106
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ 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 a host key has just been changed.
The fingerprint for the ED25519 key sent by the remote host is
SHA256:mx1ctmvoleWzmA3kVqOr+H9uIMQFPsK9eTXlnJ5fnGA.
Please contact your system administrator.
Add correct host key in /root/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /root/.ssh/known_hosts:5
remove with:
ssh-keygen -f "/root/.ssh/known_hosts" -R "192.168.0.106"
ED25519 host key for 192.168.0.106 has changed and you have requested strict checking.
Host key verification failed.

Method 1: Remove the old Key manually

We need to first check the known_hosts file and identify the Line which needs to be removed. As shown in the above output Offending ECDSA Key is in Line 5.

root@localhost:~# vi /root/.ssh/known_hosts
|1|5CmiAXPuYGM70G8z3heGuwoSs7E=|jkGqOlPtgJ2mZbAzAq/AJNADN3I= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAPzd/8/PhIgKU3FIPVEUwIyoQHOt8eJoABt0RaufdVrrPnFHHSQ6jXBRV9hSkamZSGBHPsmE3f/dY7tnpHoZUM=
|1|xHNRVs6McL0Gp80pV7a+ljscOLE=|gTJY5lhzrj4QYaBD9JA3UflX/lM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAPzd/8/PhIgKU3FIPVEUwIyoQHOt8eJoABt0RaufdVrrPnFHHSQ6jXBRV9hSkamZSGBHPsmE3f/dY7tnpHoZUM=
|1|CBAvhjKLrxeAAzM2uT8J4szRSps=|HI5xiBZaeanE8crsBtzLKBmAqXs= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAPzd/8/PhIgKU3FIPVEUwIyoQHOt8eJoABt0RaufdVrrPnFHHSQ6jXBRV9hSkamZSGBHPsmE3f/dY7tnpHoZUM=
|1|Db8TGhcXNuKRxXXwNCwjqSt1/uU=|mo9PyxWR3TIQlwud9frNGRcPWe8= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAPzd/8/PhIgKU3FIPVEUwIyoQHOt8eJoABt0RaufdVrrPnFHHSQ6jXBRV9hSkamZSGBHPsmE3f/dY7tnpHoZUM=
|1|q5/RG/dsqu+dE74tZIlw8e1ChqE=|nB0ZXIXI4K1yurS7UDC3OPfpXPI= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBNqUWv4MFC3F1saxTSdfKq7hsQrpYnndhtYKS3o9mye18Wlj9eQVioFJfjklV+k2/tyh44edzobcBbxSRIsxvb8=
|1|AyDcLMMCoc+AHSDzIyc8pPR0dHk=|6xF+Gxzl3GwwWDwA6BMUhCtayI0= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBGozD0jj2XM/ZDyI0Zo1M90Z3phgG2df2bWy166hAl5xvRGiI8gFP+G1ScJ8uRZr9AiFFGWBDWQIO/VBtmjR7Gg=
|1|3Yp+dAPXHBMy9vu5me5SsB1J3vM=|UExr+SJXdZmOSC8y4CBnOr5taqc= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFavUGGTHtoc82HQuv0u6DEEZrabdcGc8l3qjgoacRx0gvVtr5PFKHtBpGwfsuxkDxjGw5ve4cLanT9iDzRLwK0=
|1|AytaU8PXh+Lbjz5WxyWIEB/rGiE=|dusFRGTKPdkY997X+n+BMW1uQSM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBA4Lyy04vbYabkqH3V2226NKohEcKoIOjnPhWDLjBr/8Fag94xwUEAbOyWOrpFh7MfAXWW58iaq/k49CPYXP5ss=

So from the above file we need to delete Line 5 using sed -i '5d' ~/.ssh/known_hosts command as shown below.

root@localhost:~# sed -i '5d' ~/.ssh/known_hosts

Now if you again check /root/.ssh/know_hosts file then you can see Line number 5 is deleted now as can be seen from below output.

root@localhost:~# cat ~/.ssh/known_hosts
|1|5CmiAXPuYGM70G8z3heGuwoSs7E=|jkGqOlPtgJ2mZbAzAq/AJNADN3I= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAPzd/8/PhIgKU3FIPVEUwIyoQHOt8eJoABt0RaufdVrrPnFHHSQ6jXBRV9hSkamZSGBHPsmE3f/dY7tnpHoZUM=
|1|xHNRVs6McL0Gp80pV7a+ljscOLE=|gTJY5lhzrj4QYaBD9JA3UflX/lM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAPzd/8/PhIgKU3FIPVEUwIyoQHOt8eJoABt0RaufdVrrPnFHHSQ6jXBRV9hSkamZSGBHPsmE3f/dY7tnpHoZUM=
|1|CBAvhjKLrxeAAzM2uT8J4szRSps=|HI5xiBZaeanE8crsBtzLKBmAqXs= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAPzd/8/PhIgKU3FIPVEUwIyoQHOt8eJoABt0RaufdVrrPnFHHSQ6jXBRV9hSkamZSGBHPsmE3f/dY7tnpHoZUM=
|1|Db8TGhcXNuKRxXXwNCwjqSt1/uU=|mo9PyxWR3TIQlwud9frNGRcPWe8= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAPzd/8/PhIgKU3FIPVEUwIyoQHOt8eJoABt0RaufdVrrPnFHHSQ6jXBRV9hSkamZSGBHPsmE3f/dY7tnpHoZUM=
|1|AyDcLMMCoc+AHSDzIyc8pPR0dHk=|6xF+Gxzl3GwwWDwA6BMUhCtayI0= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBGozD0jj2XM/ZDyI0Zo1M90Z3phgG2df2bWy166hAl5xvRGiI8gFP+G1ScJ8uRZr9AiFFGWBDWQIO/VBtmjR7Gg=
|1|3Yp+dAPXHBMy9vu5me5SsB1J3vM=|UExr+SJXdZmOSC8y4CBnOr5taqc= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFavUGGTHtoc82HQuv0u6DEEZrabdcGc8l3qjgoacRx0gvVtr5PFKHtBpGwfsuxkDxjGw5ve4cLanT9iDzRLwK0=
|1|AytaU8PXh+Lbjz5WxyWIEB/rGiE=|dusFRGTKPdkY997X+n+BMW1uQSM= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBA4Lyy04vbYabkqH3V2226NKohEcKoIOjnPhWDLjBr/8Fag94xwUEAbOyWOrpFh7MfAXWW58iaq/k49CPYXP5ss=

Method 2: Remove Known Hosts Using ssh-keygen command

Another method is to use ssh-keygen command to resolve this error. You can remove the entry of remote host from known_hosts file using below ssh-keygen command.

root@localhost:~# ssh-keygen -f "/root/.ssh/known_hosts" -R "192.168.0.106"
# Host 192.168.0.106 found: line 5
/root/.ssh/known_hosts updated.
Original contents retained as /root/.ssh/known_hosts.old

You can use either of the above given method to remove the host key and then try connecting again. You can use the same ssh command to connect remote host and can see that you are not getting this "host key verification failed" error again.

root@localhost:~# ssh root@192.168.0.106
The authenticity of host '192.168.0.106 (192.168.0.106)' can't be established.
ED25519 key fingerprint is SHA256:mx1ctmvoleWzmA3kVqOr+H9uIMQFPsK9eTXlnJ5fnGA.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.0.106' (ED25519) to the list of known hosts.
Password:
Last login: Sat May 23 23:54:31 2020 from 192.168.0.101
NOTE: system has 1 active alert; run 'fmadm list' for details.
Oracle Corporation SunOS 5.11 11.4 Aug 2018

There is one more way to avoid "host key verification failed" error by disabling the host key check. This can be done by setting StrictHostKeyChecking option as no while using ssh command to connect remote host. This can be seen from below example.

root@localhost:~# ssh -o 'StrictHostKeyChecking no' root@192.168.0.106

NOTE:

Please do not permanently set StrictHostKeyChecking to no without knowing your system completely as this might create major security breach and make your system vulnerable for Trojan attacks. By default you will see this option set to yes

Now that we are able to login into the remote host. So let’s try to copy the public key again and check but before that we need to exit out from the remote host using exit command.

root@localhost:~# exit
logout
Connection to 192.168.0.106 closed.

As done above, we will again try to copy the ssh public key to remote host 192.168.0.106 using ssh-copy-id root@192.168.0.106 command and will see if it works this time.

root@localhost:~# ssh-copy-id root@192.168.0.106
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
Password:

Number of key(s) added: 1

Now try logging into the machine, with: "ssh 'root@192.168.0.106'"
and check to make sure that only the key(s) you wanted were added.

By seeing the above output, you can be sure that it is working fine now and no other error is visible.
 

Recommended Posts:-

10 Useful iproute2 tools examples to Manage Network Connections in Linux

Popular firewalld examples to open a port on RedHat/CentOS 7

8 Most Popular mkdir command in Linux with Examples

26 Useful Firewall CMD Examples on RedHat/CentOS 7

12 Most Popular rm command in Linux with Examples

9 useful w command in Linux with Examples

Popular Apache Kafka Architecture Explained Using 4 Basic Components

5 Easy Steps to recover LVM2 Partition , PV , VG , LVM metadata in Linux

How to compare Numbers or Integers in Bash

What happens in background when you connect a server first time using ssh

When you connect to a server for the first time, the server prompts you to confirm that you are connected to the correct system. The following example uses the ssh command to connect to a remote host named host03:

# ssh host03
The authenticity of host 'host03 (192.0.2.103)' can’t be
established. ECDSA key fingerprint is ...
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'host03,192.0.2.103' (ECDSA) to the list of known hosts.

Host validation is one of OpenSSH’s major features. The command checks to make sure that you are connecting to the host that you think you are connecting to. When you enter yes, the client appends the server’s public host key to the user’s ~/.ssh/known_hosts file, creating the ~/.ssh directory if necessary. The next time you connect to the remote server, the client compares this key to the one the server supplies. If the keys match, you are not asked if you want to continue connecting.

If someone tries to trick you into logging in to their machine so that they can sniff your SSH session, you will receive a warning similar to the following:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    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
dd:cf:50:31:7a:78:93:13:dd:99:67:c2:a2:19:22:13.
Please contact your system administrator.
Add correct host key in /home/user01/.ssh/known_hosts to get rid of this message.
Offending key in /home/lcz/.ssh/known_hosts:7
RSA host key for 192.168.219.149 has changed and you have requested strict checking.
Host key verification failed.

If you ever get a warning like this, stop and determine whether there is a reason for the remote server’s host key to change (such as if SSH was upgraded or the server itself was upgraded). If there is no good reason for the host key to change, do not try to connect to that machine until you have resolved the situation.

How to correct the “host key verification failed” error

Method 1 – removing old key manually

1. On the source server, the old keys are stored in the file ~/.ssh/known_hosts.

2. Only if this event is legitimate, and only if it is precisely known why the SSH server presents a different key, then edit the file known_hosts and remove the no longer valid key entry. Each user in the client/source server has its own known_hosts in its home directory, just remove the entry in the file of a specific user for the destination server. For example:
– If root wants to ssh to the server, just removing entry in the /root/.ssh/known_hosts file is all right.
– If testuser wants to ssh to the server, then remove the entry in the file /home/testuser/.ssh/known_hosts.

3. In my case, I will remove the the key (highlighted in red) for the destination server 192.168.219.149 from the file /home/user01/.ssh/known_hosts.

# vim /home/user01/.ssh/known_hosts
172.104.9.113 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLrY91bQOihgFZQ2Ay9KiBG0rg51/YxJAK7dvAIopRaWzFEEis3fQJiYZNLzLgQtlz6pIe2tj9m/Za33W6WirN8=
192.168.219.148 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCrY/m16MdFt/Ym51Cc7kxZW3R2pcHV1jlOclv6sXix1UhMuPdtoboj+b7+NLlTcjfrUccL+1bkg8EblYucymeU=
192.168.219.149 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBCrY/m16MdFt/Ym51Cc7kxZW3R2pcHV1jlOclv6sXix1UhMuPdtoboj+b7+NLlTcjfrUccL+1bkg8EblYucymeU=

Method 2 – removing old key using the ssh-keygen command

You can also remove the old key using the ssh-keygen command as well. The syntax to use the command is below.

$ ssh-keygen -R [hostname|IP address]

For example, In our case we will use the IP address to delete the old key.

$ ssh-keygen -R 192.168.219.149
# Host 192.168.219.149 found: line 3
/home/user01/.ssh/known_hosts updated.
Original contents retained as /home/user01/.ssh/known_hosts.old

Note : If you do not know precisely, why the SSH server presents a different key, either your known_hosts file is incorrect, or somebody must investigate this server and the network connections to understand the reason of the unexpected change.

Verify

If the remote servers asks for a confirmation to add the new key to the ~/.ssh/known_host file, it confirms that you have successfully removed the old key. If you confirm the request, the source machine adds the new key into the ~/.ssh/known_host file.

$ ssh root@192.168.219.149
The authenticity of host '192.168.219.149 (192.168.219.149)' can't be established.
ECDSA key fingerprint is SHA256:V+iGp3gwSlnpbtYv4Niq6tcMMSZivSnYWQIaJnUvHb4.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.219.149' (ECDSA) to the list of known hosts.

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

Содержание

  1. Какие бывают ошибки протокола SSH?
  2. Невозможность проверки ключа хоста
  3. Закрытие или сброс соединения
  4. Ошибка взаимодействия с хостом
  5. Заключение

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

Невозможность проверки ключа хоста

При создании SSH-соединения протокол требует, чтобы стороны идентифицировали себя. Бывает так, что от сервера поступает следующая ошибка:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ 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 a host key has just been changed.
The fingerprint for the ECDSA key sent by the remote host is
SHA256:doBAKL304WyMd8hnFc9a29r3nX9okS9BlrBJcHtuyNk.
Please contact your system administrator.
Add correct host key in /root/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /root/.ssh/known_hosts:14
ECDSA host key for 212.45.27.201 has changed and you have requested strict checking.
Host key verification failed.

Эта ошибка может возникать по нескольким причинам:

  • переустановка SSH-сервера и неполная его конфигурация;
  • восстановление сервера из резервной копии;
  • изменение IP-адреса сервера.

Очистка ключей хостов помогает решить эту проблему. Сами эти ключи хранятся на стороне клиента в файле ~/.ssh/known_hosts. Для очистки можно удалить все записи вручную. Либо можно использовать команду:

$ ssh-keygen -R host_ip

Эта команда попытается очистить соответствующую информацию о ключе хоста в файле known_hosts:

Host 123.123.123.123 found: line 14
/home/john/.ssh/known_hosts updated.
Original contents retained as /home/john/.ssh/known_hosts.old

После этих действий можно попробовать снова выполнить подключение к серверу SSH.

Закрытие или сброс соединения

Бывает так, что соединение с SSH-сервером устанавливается, однако на этапе проверки ключей сбрасывается. Эта ошибка выглядит следующим образом:

Connection closed by 123.123.123.123 port 22

Часто такая ошибка возникает по нескольким причинам:

  •  программный сбой работы SSH-сервера или он не запущен;
  • невозможность инициализировать соединение из-за отсутствия или недоступности ключей.

В данном случае необходимо проверить корректность заданной конфигурации сервера, проверить, запущен ли сам сервис. Если же с сервисом всё в порядке, то необходимо удостовериться, что SSH-ключи доступны для использования сервером. Если они отсутствуют, то необходимо их сгенерировать.

В данном случае необходимо проверить, есть ли в каталоге /etc/ssh набор файлов с именами sshd_host_*_key. Один из них должен иметь расширение *.pub.
В случае, если таких файлов нет, их нужно сгенерировать:

$ ssh-keygen -A
ssh-keygen: generating new host keys: RSA DSA ECDSA ED25519

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

Ошибка взаимодействия с хостом

Для работы протокола SSH на этапе его инициализации генерируется общий закрытый ключ. Он создаётся на основе шифрования, которое согласуется при создании подключения между сервером и клиентом. Иногда на этом этапе возникают несоответствия и на стороне клиента это приводит к следующей ошибке:

Unable to negotiate with 123.123.123.123: no matching key exchange method found.
Their offer: diffie-hellman-group1-sha1

Эта ошибка говорит о том, что сервер и клиент друг друга «не понимают». Это может быть вызвано следующими причинами:

  • список шифрования сервера был изменён или сервер его не поддерживает;
  • различные реализации (версии) протокола SSH на сервере и у клиента.

Как можно видеть, для устранения этой ошибки необходимо привести в соответствие версию клиента SSH, а также настроить шифрование для него. Если сервер использует устаревший метод шифрования, например SHA1, а у клиента по-умолчанию задействованы более совершенные методы, то это также будет вызывать ошибки протокола SSH. Для начала необходимо выяснить, действительно ли у сервера и клиента используются разные методы шифрования.
Для клиента использование методов шифрования можно настроить, используя опцию KexAlgorithms:

$ openssh -o KexAlgorithms=+diffie-hellman-group1-sha1 root@your_server_ip

Эта проблема не такая распространённая, поскольку возникает, когда версия реализации SSH-клиента более новая, чем используемая на сервере.

Заключение

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

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Learn why this error happens when trying to access a server that has been accessed previously but that has probably a new operative system installed.

The last month, i decided to upgrade the server where Our Code World is currently hosted for a genuinely better server. As i always do, i adquired the new server and started configuring it in order to migrate the old server data. After a while, i went to the administration panel of the server in their website to remove the old root key file and i noticed that the datacenter where the server was located wasn’t in america, but in France. The chosen datacenter was wrong, so i requested a new server in america. After the deployment, i installed the new operative system, but i installed the wrong version of Ubuntu (16 instead of 18.04), so i wiped once again the server🤣. After checking finally that everything that i installed the right version of Ubuntu, i tried to access the server via SSH, for my surprise once again, i ended up with another error:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    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
XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX
Please contact your system administrator.
Add correct host key in /root/.ssh/known_hosts to get rid of this message.
Offending key in /root/.ssh/known_hosts:5
RSA host key for [192.xxx.xx.xx]:22 has changed and you have requested strict checking.
Host key verification failed.

The issue is caused because you are connecting to a server where you previously were connected to, but whose RSA host changed since the last time you connected to it (i connected to the first version of the server with Ubuntu 16.04 and then tried to connected to the same server with Ubuntu 18.04 and the exception showed up). In order to prevent any security breach, you will need to remove this key from the known_hosts file of your local machine in order to connect properly.

A. Manually remove offending key

Well, deleting the known_hosts file is a valid solution as long as you don’t care about having to confirm everytime that you connect to some server that the fingerprint is valid, so don’t delete the known_hosts file. The easiest solution is to simply remove the line with the problem on the file, in our case the exception message warned us that the offending key is in the line #5:

Add correct host key in /root/.ssh/known_hosts to get rid of this message.
Offending key in /root/.ssh/known_hosts:5

So you would only need either to remove the line, using a single command like this (replace 5 with the number of your line):

sed -i '5d' ~/.ssh/known_hosts

And that’s it. Alternatively, modify the known_hosts file using a terminal editor like nano or vim and remove the line by yourself.

B. Using ssh-agent

Alternatively, you can use the ssh-keygen tool to simply remove the offending key if you know the hostname/ip:

ssh-keygen -R <SERVER_IP_OR_HOSTNAME> -f ~/.ssh/known_hosts

This should work as well to remove the warning from appearing in the terminal.

Happy coding ❤️!

SSH или Secure Shell — очень распространенный способ безопасного доступа к удаленным машинам, обычно через командную строку. Он направлен на то, чтобы ваше соединение и, следовательно, все передаваемые данные были свободны от подслушивания. Из-за этого в популярные клиенты SSH, такие как OpenSSH [https://en.wikipedia.org/wiki/OpenSSH], встроено довольно много проверок, которые гарантируют, что ваше соединение не будет скомпрометировано. Ниже приведен пример одной из этих проверок, которая определяет, когда отпечаток пальца

SSH или Secure Shell — очень распространенный способ безопасного доступа
к удаленным машинам, обычно через командную строку. Он направлен на то,
чтобы ваше соединение и, следовательно, все передаваемые данные были
свободны от подслушивания. Из-за этого в популярные клиенты SSH, такие
как OpenSSH , встроено немало
проверок, которые гарантируют, что ваше соединение не будет
скомпрометировано.

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

 $ ssh [email protected] 
 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 
 @ 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 a host key has just been changed. 
 The fingerprint for the ECDSA key sent by the remote host is 
 SHA256:hotsxb/qVi1/ycUU2wXF6mfGH++Yk7WYZv0r+tIhg4I. 
 Please contact your system administrator. 
 Add correct host key in /Users/scott/.ssh/known_hosts to get rid of this message. 
 Offending ECDSA key in /Users/scott/.ssh/known_hosts:47 
 ECDSA host key for ec2-192-168-1-1.compute-1.amazonaws.com has changed and you have requested strict checking. 
 Host key verification failed. 

Когда вы подключаетесь к серверу через SSH, он получает отпечаток ключа
ECDSA
, который затем сохраняет в вашем домашнем каталоге в
~/.ssh/known_hosts . Это делается после первого подключения к серверу,
и вам будет предложено следующее сообщение:

 $ ssh [email protected] 
 The authenticity of host 'ec2-192-168-1-1.compute-1.amazonaws.com (192.168.1.1)' can't be established. 
 ECDSA key fingerprint is SHA256:hotsxb/qVi1/ycUU2wXF6mfGH++Yk7WYZv0r+tIhg4I. 
 Are you sure you want to continue connecting (yes/no)? 

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

Но что произойдет, если ключ ECDSA сервера изменился с момента вашего
последнего подключения к нему? Это настораживает, потому что на самом
деле это может означать, что вы подключаетесь к другому серверу, не зная
об этом. Если этот новый сервер является вредоносным, он сможет
просматривать все данные, отправляемые в ваше соединение и из него,
которые могут быть использованы любым, кто настраивал сервер. Это
называется атакой «человек
посередине» .
Этот сценарий в точности соответствует сообщению «ПРЕДУПРЕЖДЕНИЕ:
ИДЕНТИФИКАЦИЯ УДАЛЕННОГО ХОЗЯКА ИЗМЕНИЛАСЬ!» сообщение пытается вас
предупредить.

Конечно, это не всегда так, и есть много причин для изменения отпечатка
ключа ECDSA для сервера. В моем случае у меня был эластичный IP-адрес на
AWS, и я назначил его другому серверу после повторного развертывания
нашего приложения. IP-адрес и имя хоста, к которым я подключался, были
одинаковыми, но базовый сервер был другим, что и заставило SSH-клиент
выдать это предупреждение.

Устранение проблемы

Если вы на 100% уверены, что это ожидаемое поведение и что нет
потенциальной проблемы с безопасностью, вам необходимо исправить
проблему, прежде чем продолжить.

Я нашел два самых простых способа решить эту проблему.

Разрешить вручную через known_hosts

  • В предупреждающем сообщении найдите строку, которая сообщает вам,
    где находится проблемный ключ ECDSA в файле known_hosts В моем
    примере в этой строке говорилось «Нарушение ключа ECDSA в
    /Users/scott/.ssh/known_hosts:47», что относится к строке 47.
  • Откройте known_hosts указанный в предупреждающем сообщении.
  • Удалить строку, указанную в предупреждающем сообщении

Удалив эту строку, у вашего SSH-клиента не будет отпечатка ключа ECDSA
для сравнения, и он снова попросит вас проверить подлинность сервера при
следующем подключении. После этого у вас будет новый отпечаток в нашем
known_hosts для этого сервера, и предупреждение исчезнет.

Разрешить с помощью ssh-keygen

Другое решение — использовать утилиту
ssh-keygen known_hosts
ключа из вашего файла known_hosts, что можно сделать с помощью следующей
команды:

 $ ssh-keygen -R [hostname-or-IP] 

Итак, в моем примере я бы использовал это так:

 $ ssh-keygen -R ec2-192-168-1-1.compute-1.amazonaws.com 

Этот метод хорош, если вы не хотите вручную изменять known_hosts , а
утилиту проще использовать, если вам нужно исправить несколько имен
хостов и IP-адресов. Он также может обрабатывать хешированные
known_hosts.old хостов в файле known_hosts.old.

Понравилась статья? Поделить с друзьями:
  • Ssh error publickey permission denied
  • Ssh error no such target
  • Ssh error no display environment variable specified
  • Ssh error network error connection refused
  • Ssh error log