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

For most of the cases, the error msg returned by the Linux would have told you what to do. For instance in the earlier answer:

my_mac:~ oivanche$ sudo ssh pi@192.168.0.45
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    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:sx1Z4xyGY9venBP6dIHAoBj0VhDOo7TUVCE2xWXpzQk.
Please contact your system administrator.
Add correct host key in /var/root/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /var/root/.ssh/known_hosts:74
ECDSA host key for 192.168.0.45 has changed and you have requested strict checking.
Host key verification failed.

It says that the remote server host key has changed – therefore your previously stored local record DOES NOT MATCH any more. For security reasons the connection is not established.

The simplest solution would be just deleted the line mentioned (line 74) in your local pc in /var/root/.ssh/known_hosts by

sudo nano /var/root/.ssh/known_hosts

You would want to deleted the line mentioned ONLY. No easier way just use your keyboard cursor and backspace or delete keys.

Once deletion is done, save it by command Ctrl+o and quit the file by command Ctrl+x.

Now reconnect to your host via ssh, using something like this:

ssh -i /Users/ben/document/key.pem root@192.168.0.45

where /Users/ben/document/key.pem is your server’s key pair you had set to use (can’t find it anymore? go to the hosting site to regenerate one) and 192.168.0.45 is your remote server IP you are connecting to.

When prompted with something like are you sure you want to add the host key permanently to this machine? type yes. Then you have updated your local key for connecting to the remote server for good.

Hope this clarifies and helps.

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.

I have set up ssh key pairs between my desktop and two servers, and from the servers to my desktop, but after reinstalling the OS on my desktop, I can’t re-establish the key-pair going into my desktop by this:

mkdir ~/.ssh
chmod 700 ~/.ssh
ssh-keygen -t 
ssh-copy-id username@server

I get the following error:

(names in italics changed to protect the innocent My desktop is Ubuntu, and I can’t find the answer here)

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ 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
ab:cd:ef:gh
Please contact your system administrator.
Add correct host key in /home/user/.ssh/known_hosts to get
rid of this message.
Offending key in /home/user/.ssh/known_hosts:1
RSA host key for user.server has changed and you have requested strict
checking.
Host key verification failed.

2240's user avatar

2240

1,5372 gold badges11 silver badges29 bronze badges

asked Nov 12, 2010 at 4:11

David LeBauer's user avatar

David LeBauerDavid LeBauer

30.8k31 gold badges115 silver badges187 bronze badges

1

ssh-keygen -R hostname

This deletes the offending key from the known_hosts

The man page entry reads:

-R hostname Removes all keys belonging to hostname from a known_hosts file. This option is useful to delete hashed hosts (see the -H option
above).

answered Dec 14, 2011 at 14:51

Rob Audenaerde's user avatar

Rob AudenaerdeRob Audenaerde

19k10 gold badges75 silver badges119 bronze badges

4

Most likely, the remote host ip or ip_alias is not in the ~/.ssh/known_hosts file. You
can use the following command to add the host name to known_hosts file.

$ssh-keyscan -H -t rsa ip_or_ipalias >> ~/.ssh/known_hosts

Also, I have generated the following script to check if the particular ip or ipalias is in the know_hosts file.

#!/bin/bash
#Jason Xiong: Dec 2013   
# The ip or ipalias stored in known_hosts file is hashed and   
# is not human readable.This script check if the supplied ip    
# or ipalias exists in ~/.ssh/known_hosts file

if [[ $# != 2 ]]; then
   echo "Usage: ./search_known_hosts -i ip_or_ipalias"
   exit;
fi
ip_or_alias=$2;
known_host_file=/home/user/.ssh/known_hosts
entry=1;

cat $known_host_file | while read -r line;do
  if [[ -z "$line" ]]; then
    continue;
  fi   
  hash_type=$(echo $line | sed -e 's/|/ /g'| awk '{print $1}'); 
  key=$(echo $line | sed -e 's/|/ /g'| awk '{print $2}');
  stored_value=$(echo $line | sed -e 's/|/ /g'| awk '{print $3}'); 
  hex_key=$(echo $key | base64 -d | xxd -p); 
  if  [[ $hash_type = 1 ]]; then      
     gen_value=$(echo -n $ip_or_alias | openssl sha1 -mac HMAC 
         -macopt hexkey:$hex_key | cut -c 10-49 | xxd -r -p | base64);     
     if [[ $gen_value = $stored_value ]]; then
       echo $gen_value;
       echo "Found match in known_hosts file : entry#"$entry" !!!!"
     fi
  else
     echo "unknown hash_type"
  fi
  entry=$((entry + 1));
done

Aziz Alfoudari's user avatar

answered Dec 24, 2013 at 3:54

Jason Xiong's user avatar

1

Step1:$Bhargava.ssh#

ssh-keygen -R 199.95.30.220

step2:$Bhargava.ssh #

ssh-copy-id hostname@199.95.30.220

          Enter the the password.........

step3: Bhargava .ssh #

ssh hostname@199.95.30.220

Welcome to Ubuntu 14.04.3 LTS (GNU/Linux 3.13.0-68-generic x86_64) * Documentation: https://help.ubuntu.com/ Ubuntu 14.04.3 LTS server : 228839 ip : 199.95.30.220 hostname : qt.example.com System information as of Thu Mar 24 02:13:43 EDT 2016 System load: 0.67 Processes: 321 Usage of /home: 5.1% of 497.80GB Users logged in: 0 Memory usage: 53% IP address for eth0: 199.95.30.220 Swap usage: 16% IP address for docker0: 172.17.0.1 Graph this data and manage this system at: https://landscape.canonical.com/ Last login: Wed Mar 23 02:07:29 2016 from 103.200.41.50

hostname@qt:~$

answered Apr 22, 2016 at 5:36

Batchu Bhargava's user avatar

1

If you’re sure the server is correct, sed -i 1d ~/.ssh/known_hosts will delete line 1 of your local ~/.ssh/known_hosts. The new correct key will be added to the file the next time you connect.

answered Nov 12, 2010 at 5:54

ephemient's user avatar

ephemientephemient

197k38 gold badges278 silver badges391 bronze badges

3

Also sometimes there is situation when you are working on serial console, then checking above command in verbose mode -v will show you /dev/tty does not exists, while it does.

In above case just remove /dev/tty and create a symlink of /dev/ttyS0 to /dev/tty.

answered May 27, 2012 at 13:00

peeyush's user avatar

peeyushpeeyush

2,8333 gold badges24 silver badges43 bronze badges

Its means your remote host key was changed (May be host password change),

Your terminal suggested to execute this command as root user

$ ssh-keygen -f "/root/.ssh/known_hosts" -R [www.website.net]:4231

You have to remove that host name from hosts list on your pc/server. Copy that suggested command and execute as a root user.

$ sudo su                                                            // Login as a root user

$ ssh-keygen -f "/root/.ssh/known_hosts" -R [www.website.net]:4231   // Terminal suggested command execute here
Host [www.website.net]:4231 found: line 16 type ECDSA
/root/.ssh/known_hosts updated.
Original contents retained as /root/.ssh/known_hosts.old

$ exit                                                               // Exist from root user

$ sudo ssh root@www.website.net -p 4231                              // Try again

I Hope this works.

answered Aug 14, 2016 at 5:00

Jaykumar Patel's user avatar

Jaykumar PatelJaykumar Patel

26.6k12 gold badges73 silver badges76 bronze badges

This issue arises when the host key is expired or changed. you can remove the keys that host is using and try to ssh again, so that you are adding new key that is known to both client and server.

You can check the keys associated with your hosts with cat /.ssh/known_hosts . Now, You can remove the hosts keys manually or using the ssh-keygen option. You can do either of the following option.

  1. Manual removal of keys

    vim /.ssh/known_hosts

delete the key that is associated with your host.

  1. Remove key using ssh-keygen

    ssh-keygen -R your_host_or_host_ip

This will remove your key associated with the host.

Now, you can ssh to your host as usual and you will be asked if you want to continue to this host. Once your enter yes, this host will be added to your/.ssh/known_hosts with updated key. By now, you should be your host.

answered Dec 11, 2019 at 2:36

Sbk3824's user avatar

Sbk3824Sbk3824

1,2291 gold badge14 silver badges24 bronze badges

First you should remove existing key. SSH keys in most of Linux-based OS will be saved this file “/root/.ssh/known_hosts”, so in order to remove the key related to host the following command will be used:

ssh-keygen -f "/root/.ssh/known_hosts" -R [Hostname]

Regards
K1

answered Apr 9, 2018 at 13:04

Keivan's user avatar

KeivanKeivan

1,2461 gold badge16 silver badges29 bronze badges

rm -f /home/user/.ssh/known_hosts

or open it up and delete the entry for the offending ip/hostname

(P.S. It tells you exactly this in the error message you posted)

answered Nov 12, 2010 at 4:34

Matt Phillips's user avatar

Matt PhillipsMatt Phillips

11.2k10 gold badges46 silver badges71 bronze badges

4

When you try to connect your remote server with ssh:

$ ssh username@ip_address

then the error raise, to solve it:

$ ssh-keygen -f "/home/local_username/.ssh/known_hosts" -R "ip_address"

answered Dec 30, 2019 at 8:56

Hu Xixi's user avatar

Hu XixiHu Xixi

1,7492 gold badges20 silver badges28 bronze badges

Task Passwordless authentication for suer.

Error : Host key verification failed.

Source :10.13.1.11
Target : 10.13.1.35

Temporary workaround :

[user@server~]$ ssh user@10.13.1.35
The authenticity of host ‘10.13.1.35 (10.13.1.35)’ can’t be established.
RSA key fingerprint is b8:ba:30:46:a9:ab:70:12:1a:f2:f1:61:69:73:0a:19.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ‘10.13.1.35’ (RSA) to the list of known hosts.

Try to authenticate user again…it will work.

answered Nov 9, 2019 at 9:10

user12346922's user avatar

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.

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