Validating host keys

Top  Previous  Next

When connecting to an SSH server using the Ssh class you may define that your login credentials only be submitted to hosts that provide a host key with a recognized fingerprint.  This prevents the possibility of a man in the middle attack.  You may specify what host keys are allowed using a SshHostKeys instance and the SshParameters.HostKeys property.

 

Example

 

// create new SshParameters instance

SshParameters params = new SshParameters(hostname, port, username, password);

 

// create new SshHostKeys instance

SshHostKeys keys = new SshHostKeys();

 

// add valid hostname and fingerprint to host keys

keys.AddKey(Dns.GetHostByName(hostname), "72:65:72:6b:aa:4c:34:21:6f:e8:e7:45:ca:d6:ae:1a");

 

// require that host provide specified fingerprint, not allowing unknown keys to be added

sshParams.SetHostKeys(keys, false);

 

// create a new Ssh instance

Ssh ssh = new Ssh(params);

 

// establish connection

ssh.Connect();

 

// gets updated host keys (if updated)

keys = ssh.HostKeys;

 

// print all hosts and keys

IEnumerator iHosts = keys.GetHosts();

while (iHosts.MoveNext())

{

 DictionaryEntry entry = (DictionaryEntry)iHosts.Current;

           IPHostEntry host = (IPHostEntry)entry.Key;

           ArrayList keysForHost = (ArrayList)entry.Value;

             

           Console.Out.WriteLine("Host: {0}", host.HostName);

 

           IEnumerator listEnum = keysForHost.GetEnumerator();

          while (listEnum.MoveNext())

           {

                 Console.Out.WriteLine(listEnum.Current);

           }              

}

 

 

See also

 

Obtaining host key fingerprint