edtFTPnet/PRO - Secure FTP component for .NET | Free Trial | Pricing

How to use SFTP (with server validation - known hosts)

The topic How to use SFTP (with server validation) gives an overview of server validation. Many SSH implementations use a file called known_hosts which is loaded by clients to validate servers. Typically, this file is generated when the client first connects to a server - a prompt asks if the server should be added to the list of known hosts.

The known_hosts file contains a list of approved servers and their public keys. Setting ServerValidation to Automatic instructs the client to use this list to validate the servers that it connects to. Setting ServerValidation to AutomaticNoNameCheck is similar, however the server name is ignored in the validation process.

A single line in a known_hosts file looks like this:

edtmobile,10.0.0.3 ssh-rsa
AAAAB3NzaC1yc2EAAAABIwAAAIEAt60CtjBMxiOOqgqfFtKZHY3g99uZpuh5E143FTO4dw+EHWNKemoWq59FMFMIZfSLyUpWmsjVT3PP1bczOXP1OSn967kxLB/w7Xr84B1ZrTLwuR/ilq73HpgO7A8pdEJN7ybprzhs5CBEgaLQo2pOxfqRYyc8TO2ADnZ1WwtjW48=

The first field is the hostname, i.e. the SSH server. The IP address is also listed - a number of comma separated hostnames and IP addresses can be listed.

The second field is the applicable public key algorithm -"ssh-rsa" (for RSA key pairs) or "ssh- dss" (for DSA key pairs).

The third field is the public key encoded using base 64.

The known_hosts file normally consists of multiple lines, one for each of the hosts that the client may wish to connect to. It is quite typical for a host to have entries in two lines, so that both RSA and DSA public keys can be listed.

As noted, public keys are managed by the KnownHostsManager, available in SecureFTPConnection's KnownHosts property.

The KnownHostsManager has a property called KnownHostsFile. The path of the known_hosts file should be assigned to this property to load the known hosts in that file:

ftpConnection.KnownHosts.KnownHostsFile = "C:\\myhome\\.ssh\\known_hosts";

If another known_hosts file is subsequently assigned to this property, its contents will be added to the current list of known hosts.

To clear out the current list of known hosts, use the KnownHostsManager's ClearKnownHosts() method, e.g.

ftpConnection.KnownHosts.ClearKnownHosts();

Use WriteKnownHosts() to write the current contents of the known hosts lists to a file:

ftpConnection.KnownHosts.WriteKnownHosts("myfilename");

Server public keys can also be maintained in their own file and explicitly added to the KnownHostsManager via AddKnownHost. See How to use SFTP (with server validation - public key files).

If hosts are loaded via KnownHostsFile and also by AddKnownHost, the combined list can be merged into one known_hosts file by using WriteKnownHosts().