Rants of a madman » 2008 » January

Archive for January, 2008

Jan
4

I run DHCP at home. Having a crappy linksys router, every time i reboot it, all DHCP leases are lost. As a consequence all SSH servers on my home net gives me this 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
de:ad:be:ef:ff:59:fe:1b:39:55:fe:e5:ac:6b:13:fe.
Please contact your system administrator.
Add correct host key in /home/dan/.ssh/known_hosts to get rid of this message.
Offending key in /home/dan/.ssh/known_hosts:39
RSA host key for 192.168.1.51 has changed and you have requested strict checking.
Host key verification failed.

Finally i got fed up with manually editing my known_hosts file and deleting the conflicting line every time. I started by googling to see what others were doing, but it appears that people just edit the file like me. So i hacked up a shell script to do it for me.

EDIT: Actually, the correct way of doing this (and easy way) is simply “ssh-keygen -R”. I kept this script online anyway, because the new regex support in bash is pretty cool and this script serves as a great example.

ssh_keyclean.sh:

#!/bin/bash
DATA="`ssh $1 echo 2>&1|grep known_hosts:`"

if [[ "$DATA" =~ ([^ ]+):([0-9]+) ]]
then
        echo "SSH KeyCleaner v. 0.1";
        echo -n "Delete key from line"
        echo -n " ${BASH_REMATCH[2]} in"
        echo -n " ${BASH_REMATCH[1]}? "
        read -n1 -p"(y/n) : " A
        echo
        if [ "$A" == "y" ]
        then
                sed -i " ${BASH_REMATCH[2]}d"  ${BASH_REMATCH[1]}
                echo "Cleaning"
        fi;
else
        echo "Bad output from ssh command. Sorry.";
fi;

Copy and paste this into a file, ie. /usr/bin/ssh_keyclean.sh (and remember to use an editor that keeps the backquotes .”joe” doesnt) then “chmod +x /usr/bin/ssh_keyclean.sh”

Whenever you get the message that the key has changed, all you have to do is type:

$ ssh_keyclean.sh <ip_address>

eg.

$ ssh_keyclean.sh 192.168.1.51

How it works:

It runs the ssh command, grepping the line containing “known_hosts:”. It then uses bash’s new built-in regex support to extract 2 vars: The filename and the linenumber. Lastly it prompts you if youre sure, and if you are, it uses “sed” to delete the linenumber reported by ssh in the ~/.ssh/known_hosts file.

Requirements:

  • Bash shell v. 3+

Tested on Ubuntu Linux. Should work on all Linux distro releases newer than ~2 years i guess.

Let me know if you find it useful.



  - Dan