Skip to main content

Server identity verification

Download sample

Download source code for demo application: 04-server-identity.zip

In the previous article we were able to make file transfer from and to SFTP server. But the code has potential severe security vulnerability: it does not verify the server identity.

In the world of certificates and certificate authorities, like with HTTPS or FTPS, there is complicated infrastructure we can rely on when verifying server identity. There are trusted certificate authorities, who should be able to verify that the requestor has control over the domain they require certificates for.

SFTP does normally have nothing like that. Every server has its own key, of course, but there is no infrastructure above them. You have to manually mark certain keys as trusted.

Server identity verification with command line

We can see the process when using console commands like ssh or sftp.

Start the Rebex Tiny SFTP server and open Terminal and enter the following command to connect to server localhost as user tester:

sftp tester@localhost

If it's the first time we are connecting to this server, the following message is displayed:

The authenticity of host 'localhost (::1)' can't be established.
RSA key fingerprint is SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])?

The main information is on the second line. The sftp command computed SHA-256 hash of the RSA public key provided by the server. You are now asked to confirm, if the key is correct.

In the ideal world, you should get the hash in advance, so you can compare it with this value, to be sure you have the right key. Usually, you don't have the key in advance, so you'll confirm it's correct, hoping nobody is attacking you this time. If it will change in the future, you'll be notified.

You can answer in three ways:

  • Type yes and press Enter. You are confirming that the fingerprint is what you expected.
  • Type no and press Enter. You do not trust this fingerprint and the SFTP session will end.
  • Type the known fingerprint and press Enter. If it will match the received value, the connection will proceed.

For now, type yes and press Enter. The command will connect. Use the bye command to disconnect:

The authenticity of host 'localhost (::1)' can't be established.
RSA key fingerprint is SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])?
Warning: Permanently added 'localhost' (RSA) to the list of known hosts.
(tester@localhost) Password:
Connected to localhost.
sftp> bye

If you will connect again to the same host with the same key, you would be connected right away, because your computer remembers it. By default, list of all known hosts is stored in your user profile, in the file ~/.ssh/known_hosts. The file does not have any extension, which is kind of unusual on Windows, but fairly common on Linux.

On Windows, the file is located at C:\Users\<username>\.ssh\known_hosts. It's a plain text file, where each key has a single line, like:

localhost ssh-rsa AAAAB3NzaC1yc2E...

Here:

  • localhost is the host name.
  • ssh-rsa is name of cryptographic algorithm used for authentication.
  • The last string is Base64 encoded public key
info

The public key does not match the value displayed above. In the known_hosts file, entire public key is stored. The displayed value is SHA-256 hash of this key.

Stop the Rebex Tiny SFTP Server and exit the program. It's not enough to just stop the server, you have to close the running binary. Then delete the following files in the folder where RebexTinySftpServer.exe is:

  • server-private-key-rsa.ppk
  • server-private-key-dss.ppk

These are the key files the server uses. They contain both private and public keys.

Run the Rebex Tiny SFTP Server and click the Start button. The server will automatically generate new random keys, different from the previous ones.

Try to connect from command line again:

sftp testuser@localhost

The command will refuse to connect and will display message similar to:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ 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
SHA256:yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy.
Please contact your system administrator.
Add correct host key in C:\\Users\\Altair/.ssh/known_hosts to get rid of this message.
Offending RSA key in C:\\Users\\Altair/.ssh/known_hosts:14
Host key for localhost has changed and you have requested strict checking.
Host key verification failed.
Connection closed

The error message says everything important. The server key changed from the previous value, which is highly unusual.

  • It might be expected change. The previous key might be compromised and was generated anew. Or the server was reinstalled and the previous key was not retained.
  • You may be under attack. Attacker is redirecting the connection to their own server, performing man in the middle attack. They are unable to spoof the original server key, so their key differs and the command warns you about it. If you will connect, the attacker will be able to gain your user name and password (if you use it for authentication) and potentially other useful information (ie. you might upload some files there).

You should now decide which of these happened. You should contact the server administrator and ask them, if they did something unusual, which could result in the server key change.


If you are sure that the key change was legitimate, delete the old key from known_host file. The error message tells you where the file is located (in my case C:\Users\Altair\.ssh\known_hosts) and the number of line, where the old key is (in my case line number 14).

Delete the line and connect again. You will be asked to confirm the new key and if you do so, you will be connected and the new key will be stored in the authorized_hosts file.

Server identity verification with Rebex SFTP

To ensure we are not being attacked, we have to implement similar logic in our own SFTP client. Create a new .NET console application named Demo.ServerIdentity.

Install NuGet package Rebex.Sftp.

Either use the following command in Package Manager Console:

Install-Package Rebex.Sftp

or the following command in terminal:

dotnet add package Rebex.Sftp

Add the following code to Program.cs:

using Rebex.Net;

const string ServerName = "localhost";
const string UserName = "tester";
const string Password = "password";

Rebex.Licensing.Key = "Get trial key at https://www.rebex.net/support/trial/";

using var ftp = new Sftp();

Console.Write("Connecting to SFTP server...");
await ftp.ConnectAsync(ServerName);
Console.WriteLine("OK");

Console.Write($"Logging in user {UserName}...");
await ftp.LoginAsync(UserName, Password);
Console.WriteLine("OK");

Console.Write("Disconnecting...");
await ftp.DisconnectAsync();
Console.WriteLine("OK");

This code will try to connect, authenticate using username and password and disconnect. This is the basic skeleton you'll use for working with SFTP server.

Run the application. It will print the following messages:

Connecting to SFTP server...OK
Logging in user tester...OK
Disconnecting...OK

Displaying the server connection info

The Sftp class has ServerKey property, which offers us some useful information about the server key, the most important being KeyAlgorithmId (the cryptographic algorithm being used) and Fingerprint, which is the SHA-256 fingerprint. Using the GetPublicKey method we can get the raw public key in binary format.

Modify the Program.cs file to display the key information:

using Rebex.Net;

const string ServerName = "localhost";
const string UserName = "tester";
const string Password = "password";

Rebex.Licensing.Key = "Get trial key at https://www.rebex.net/support/trial/";

using var ftp = new Sftp();

Console.Write("Connecting to SFTP server...");
await ftp.ConnectAsync(ServerName);
Console.WriteLine("OK");

var key = ftp.ServerKey.GetPublicKey();
var encodedKey = Convert.ToBase64String(key);

Console.WriteLine($" Algorithm ID: {ftp.ServerKey.KeyAlgorithmId}");
Console.WriteLine($" Key fingerprint: {ftp.ServerKey.Fingerprint}");
Console.WriteLine($" Raw key: {encodedKey}");

Console.Write($"Logging in user {UserName}...");
await ftp.LoginAsync(UserName, Password);
Console.WriteLine("OK");

Console.Write("Disconnecting...");
await ftp.DisconnectAsync();
Console.WriteLine("OK");

Run the program. It will display the connection information, which should match what we did see when working with sftp command and what is in the known_hosts file:

Connecting to SFTP server...OK
Algorithm ID: ssh-rsa
Key fingerprint: yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
Raw key: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz...
Logging in user tester...OK
Disconnecting...OK

Based on this information alone, we can perform simple verification of server identity. We can store the expected key (or just its fingerprint) somewhere and then check it. If it does not match, do not connect and alert the operator.

Working with the known_hosts file

Better idea is to work with the standard OpenSSH known_hosts file and honor the overal system configuration. As seen in official specification, the file structure is bit more complex than outlined above, allowing for things such as key comments, markers, multiple hosts per key, hashed host names etc.

We will write simplified implementation, which will not support some less-used features. We will support:

  • Markers
  • Key comments
  • Multiple host names per key

We will not support matching the host names with wildcards, non-standard port numbers etc.

Create a new class KnownHostEntry, which will represent single line in the known_hosts file:

namespace Demo.ServerIdentity;

public class KnownHostEntry {
public KnownHostMarker Marker { get; set; } = KnownHostMarker.None;

public string[] Hostnames { get; set; } = [];

public string KeyType { get; set; } = string.Empty;

public string PublicKey { get; set; } = string.Empty;

public string? Comment { get; set; }
}

public enum KnownHostMarker {
None,
CertAuthority,
Revoked
}

Create a new class KnownHostsStore to handle the file itself. It will have two constructors. Parameterless constructor will use the default location of known_hosts file in user profile. Or the file name can be specified in another constructor overload.

namespace Demo.ServerIdentity;

public class KnownHostsStore {

public KnownHostsStore() {
var userProfilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
this.FileName = Path.Combine(userProfilePath, ".ssh", "known_hosts");
}

public KnownHostsStore(string fileName) {
this.FileName = fileName;
}

public string FileName { get; }

}

Add helper method Load, which will parse the known_hosts file and return entries:

namespace Demo.ServerIdentity;

public class KnownHostsStore {

public KnownHostsStore() {
var userProfilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
this.FileName = Path.Combine(userProfilePath, ".ssh", "known_hosts");
}

public KnownHostsStore(string fileName) {
this.FileName = fileName;
}

public string FileName { get; }

private IEnumerable<KnownHostEntry> Load() {
// If the file doesn't exist, we don't return any entries
if (!File.Exists(this.FileName)) yield break;

// Read all lines from the known_hosts file
var lines = File.ReadAllLines(this.FileName);

// Parse each line to create KnownHostEntry objects
foreach (var line in lines) {
var trimmed = line.Trim();

// Skip empty lines and comments
if (string.IsNullOrEmpty(trimmed) || trimmed.StartsWith("#")) continue;

// Split the line into parts, handling markers and ensuring we have enough parts for a valid entry
var parts = trimmed.Split([' '], StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 3) continue;

// Check for markers and determine the starting index for hostnames
var marker = KnownHostMarker.None;
var startIndex = 0;
if (parts[0].StartsWith("@")) {
if (parts[0] == "@cert-authority") marker = KnownHostMarker.CertAuthority;
if (parts[0] == "@revoked") marker = KnownHostMarker.Revoked;
startIndex = 1;

// Ensure that we have enough parts for a valid entry after accounting for the marker
if (parts.Length < 4) continue;
}

// Extract hostnames, key type, public key, and optional comment
var entry = new KnownHostEntry {
Marker = marker,
Hostnames = parts[startIndex].Split(',').Select(h => h.Trim()).ToArray(),
KeyType = parts[startIndex + 1],
PublicKey = parts[startIndex + 2]
};
if (parts.Length > startIndex + 3) entry.Comment = parts[startIndex + 3];

yield return entry;
}

}

}

Add the VerifyHost method, which will search the known_hosts file and return one of the following results:

  • Success - The host is known and the key matches.
  • HostNotFound - The host is not in the known_hosts file.
  • HostKeyMismatch - The host is known but the key does not match.
  • HostRevoked - The host is marked as revoked.
  • InvalidEntry - The host is marked as a certificate authority.
using Rebex.Net;

namespace Demo.ServerIdentity;

public class KnownHostsStore {

public KnownHostsStore() {
var userProfilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
this.FileName = Path.Combine(userProfilePath, ".ssh", "known_hosts");
}

public KnownHostsStore(string fileName) {
this.FileName = fileName;
}

public string FileName { get; }

public HostVerificationResult VerifyHost(string host, SshPublicKey key) {
if (string.IsNullOrEmpty(host)) throw new ArgumentException("Host cannot be null or empty.", nameof(host));

// Load known host entries from the file
var entries = this.Load();

// Find all entries that match the given host (case-insensitive)
var hostEntries = entries.Where(e => e.Hostnames.Contains(host, StringComparer.OrdinalIgnoreCase)).ToList();

// If no entries are found for the host, return HostNotFound
if (hostEntries.Count == 0) return HostVerificationResult.HostNotFound;

// Find the first entry that matches the public key
var keyString = Convert.ToBase64String(key.GetPublicKey());
var matchingEntry = hostEntries.FirstOrDefault(e => e.PublicKey == keyString);

// If a matching entry is not found, return mismathc
if (matchingEntry == null) return HostVerificationResult.HostKeyMismatch;

// If the entry is marked as revoked, return revoked
if (matchingEntry.Marker == KnownHostMarker.Revoked) return HostVerificationResult.HostRevoked;

// If the entry is marked as a certificate authority, return invalid entry
if (matchingEntry.Marker == KnownHostMarker.CertAuthority) return HostVerificationResult.InvalidEntry;

// If we found a matching entry and it's not revoked or a certificate authority, return success
return HostVerificationResult.Success;
}

private IEnumerable<KnownHostEntry> Load() {
// If the file doesn't exist, we don't return any entries
if (!File.Exists(this.FileName)) yield break;

// Read all lines from the known_hosts file
var lines = File.ReadAllLines(this.FileName);

// Parse each line to create KnownHostEntry objects
foreach (var line in lines) {
var trimmed = line.Trim();

// Skip empty lines and comments
if (string.IsNullOrEmpty(trimmed) || trimmed.StartsWith("#")) continue;

// Split the line into parts, handling markers and ensuring we have enough parts for a valid entry
var parts = trimmed.Split([' '], StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 3) continue;

// Check for markers and determine the starting index for hostnames
var marker = KnownHostMarker.None;
var startIndex = 0;
if (parts[0].StartsWith("@")) {
if (parts[0] == "@cert-authority") marker = KnownHostMarker.CertAuthority;
if (parts[0] == "@revoked") marker = KnownHostMarker.Revoked;
startIndex = 1;

// Ensure that we have enough parts for a valid entry after accounting for the marker
if (parts.Length < 4) continue;
}

// Extract hostnames, key type, public key, and optional comment
var entry = new KnownHostEntry {
Marker = marker,
Hostnames = parts[startIndex].Split(',').Select(h => h.Trim()).ToArray(),
KeyType = parts[startIndex + 1],
PublicKey = parts[startIndex + 2]
};
if (parts.Length > startIndex + 3) entry.Comment = parts[startIndex + 3];

yield return entry;
}

}

}

public enum HostVerificationResult {
Success,
HostNotFound,
HostKeyMismatch,
HostRevoked,
InvalidEntry
}

Add the AddHost method, which will add a new line at the end of the known_hosts file with the new host entry. If the file already exists, it will make backup of it to known_hosts.old.

using Rebex.Net;

namespace Demo.ServerIdentity;

public class KnownHostsStore {

public KnownHostsStore() {
var userProfilePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
this.FileName = Path.Combine(userProfilePath, ".ssh", "known_hosts");
}

public KnownHostsStore(string fileName) {
this.FileName = fileName;
}

public string FileName { get; }

public HostVerificationResult VerifyHost(string host, SshPublicKey key) {
if (string.IsNullOrEmpty(host)) throw new ArgumentException("Host cannot be null or empty.", nameof(host));

// Load known host entries from the file
var entries = this.Load();

// Find all entries that match the given host (case-insensitive)
var hostEntries = entries.Where(e => e.Hostnames.Contains(host, StringComparer.OrdinalIgnoreCase)).ToList();

// If no entries are found for the host, return HostNotFound
if (hostEntries.Count == 0) return HostVerificationResult.HostNotFound;

// Find entry that matches the public key
var keyString = Convert.ToBase64String(key.GetPublicKey());
var matchingEntry = hostEntries.SingleOrDefault(e => e.PublicKey == keyString);

// If a matching entry is not found, return mismathc
if (matchingEntry == null) return HostVerificationResult.HostKeyMismatch;

// If the entry is marked as revoked, return revoked
if (matchingEntry.Marker == KnownHostMarker.Revoked) return HostVerificationResult.HostRevoked;

// If the entry is marked as a certificate authority, return invalid entry
if (matchingEntry.Marker == KnownHostMarker.CertAuthority) return HostVerificationResult.InvalidEntry;

// If we found a matching entry and it's not revoked or a certificate authority, return success
return HostVerificationResult.Success;
}

public void AddHost(string host, SshPublicKey key) {
if (string.IsNullOrEmpty(host)) throw new ArgumentException("Host cannot be null or empty.", nameof(host));

// Convert the public key to a base64 string
var keyString = Convert.ToBase64String(key.GetPublicKey());

// Create a new line with known host
var newLine = string.Join(" ", host, key.KeyAlgorithmId, keyString);

// Create a backup of the existing known_hosts file if it exists
if (File.Exists(this.FileName)) {
var backupFileName = this.FileName + ".old";
File.Copy(this.FileName, backupFileName, overwrite: true);
}

// If the directory for the known_hosts file does not exist, create it
var directory = Path.GetDirectoryName(this.FileName);
if (directory != null) Directory.CreateDirectory(directory);

// Append the new line to the known_hosts file
File.AppendAllLines(this.FileName, [newLine]);
}

private IEnumerable<KnownHostEntry> Load() {
// If the file doesn't exist, we don't return any entries
if (!File.Exists(this.FileName)) yield break;

// Read all lines from the known_hosts file
var lines = File.ReadAllLines(this.FileName);

// Parse each line to create KnownHostEntry objects
foreach (var line in lines) {
var trimmed = line.Trim();

// Skip empty lines and comments
if (string.IsNullOrEmpty(trimmed) || trimmed.StartsWith("#")) continue;

// Split the line into parts, handling markers and ensuring we have enough parts for a valid entry
var parts = trimmed.Split([' '], StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 3) continue;

// Check for markers and determine the starting index for hostnames
var marker = KnownHostMarker.None;
var startIndex = 0;
if (parts[0].StartsWith("@")) {
if (parts[0] == "@cert-authority") marker = KnownHostMarker.CertAuthority;
if (parts[0] == "@revoked") marker = KnownHostMarker.Revoked;
startIndex = 1;

// Ensure that we have enough parts for a valid entry after accounting for the marker
if (parts.Length < 4) continue;
}

// Extract hostnames, key type, public key, and optional comment
var entry = new KnownHostEntry {
Marker = marker,
Hostnames = parts[startIndex].Split(',').Select(h => h.Trim()).ToArray(),
KeyType = parts[startIndex + 1],
PublicKey = parts[startIndex + 2]
};
if (parts.Length > startIndex + 3) entry.Comment = parts[startIndex + 3];

yield return entry;
}

}

}

public enum HostVerificationResult {
Success, // The host is known and the key matches
HostNotFound, // The host is not in the known_hosts file
HostKeyMismatch, // The host is known but the key does not match
HostRevoked, // The host is marked as revoked
InvalidEntry // The host is marked as a certificate authority
}

Verify the server identity with standard known_hosts file

Now we can finish our example by respecting the system configuration in the known_hosts file. We will implement the following logic:

  • If the host is known and the key matches, it will connect.
  • If the host is uknonwn, it will store its key in the file and then it will connect.
  • In other cases it will show an error message and won't connect.

Modify the Program.cs file to check the key against known_hosts file and act accordingly. If the result could lead to security risk, the application is terminated with non-zero exit code to indicate a problem.

using Rebex.Net;

const string ServerName = "localhost";
const string UserName = "tester";
const string Password = "password";

Rebex.Licensing.Key = "Get trial key at https://www.rebex.net/support/trial/";

using var ftp = new Sftp();

Console.Write("Connecting to SFTP server...");
await ftp.ConnectAsync(ServerName);
Console.WriteLine("OK");

var key = ftp.ServerKey.GetPublicKey();
var encodedKey = Convert.ToBase64String(key);

Console.WriteLine($" Algorithm ID: {ftp.ServerKey.KeyAlgorithmId}");
Console.WriteLine($" Key fingerprint: {ftp.ServerKey.Fingerprint}");
Console.WriteLine($" Raw key: {encodedKey}");

// Verify the server's host key against the known hosts store
var knownHostsStore = new Demo.ServerIdentity.KnownHostsStore();
var verificationResult = knownHostsStore.VerifyHost(ServerName, ftp.ServerKey);
switch (verificationResult) {
case Demo.ServerIdentity.HostVerificationResult.Success:
Console.WriteLine("Key was verified.");
break;
case Demo.ServerIdentity.HostVerificationResult.HostNotFound:
Console.Write("Adding host to known_hosts...");
knownHostsStore.AddHost(ServerName, ftp.ServerKey);
Console.WriteLine("OK");
break;
case Demo.ServerIdentity.HostVerificationResult.HostKeyMismatch:
Console.WriteLine("Host key mismatch!");
Console.WriteLine("WARNING: The server's host key does not match the expected key. This could indicate a potential security problem. The connection will be terminated to prevent potential security risks.");
Environment.Exit(1);
break;
case Demo.ServerIdentity.HostVerificationResult.HostRevoked:
Console.WriteLine("Host key revoked!");
Console.WriteLine("WARNING: The server's host key has been revoked. This indicates a potential security problem. The connection will be terminated to prevent potential security risks.");
Environment.Exit(1);
break;
case Demo.ServerIdentity.HostVerificationResult.InvalidEntry:
Console.WriteLine("Invalid known host entry!");
Console.WriteLine("WARNING: The known host entry for this server is invalid (marked as a certificate authority). This indicates a potential security problem. The connection will be terminated to prevent potential security risks.");
Environment.Exit(1);
break;
}

Console.Write($"Logging in user {UserName}...");
await ftp.LoginAsync(UserName, Password);
Console.WriteLine("OK");

Console.Write("Disconnecting...");
await ftp.DisconnectAsync();
Console.WriteLine("OK");
tip

In real world application, you might want to use different scenarios. For example do not add unknown key silently and automatically, or maintain your private equivalent of known_hosts file, separate from the default one.

Run the program. If you did everything in this article, the host should now be known to your system and everything should just work:

Connecting to SFTP server...OK
Algorithm ID: ssh-rsa
Key fingerprint: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Raw key: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz...
Key was verified.
Logging in user tester...OK
Disconnecting...OK

Now delete the localhost line in known_hosts file and run the program again. The line should be added again by our program.

Connecting to SFTP server...OK
Algorithm ID: ssh-rsa
Key fingerprint: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Raw key: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz...
Adding host to known_hosts...OK
Logging in user tester...OK
Disconnecting...OK

Now generate a new set of keys for the Tiny SFTP Server by quitting the program, deleting the server-private-key-*.ppk files and restarting the server.

Run the program. It display the warning message and disconnect:

Connecting to SFTP server...OK
Algorithm ID: ssh-rsa
Key fingerprint: nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Raw key: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz...
Host key mismatch!
WARNING: The server's host key does not match the expected key. This could indicate a potential security problem. The connection will be terminated to prevent potential security risks.

Alternative approach using FingerprintCheck event

There is alternative approach for server identity checking. The Sftp class has FingerprintCheck event, which is fired during the connection process.

Its event handler receives the SshFingerpringEventArgs argument, which has two useful properties:

  • ServerKey, which is instance of SshPublicKey, useful for checking.
  • Accept, which can be set to true if the key is valid and we are supposed to proceed or to false, if the key is not valid and the Connect or ConnectAsync methods are supposed to throw Rebex.Net.SshException.

Modify the Program.cs code to employ a strict checking using the event. The key has to be in the known_hosts file, otherwise the connection is not allowed:

using Rebex.Net;

const string ServerName = "localhost";
const string UserName = "tester";
const string Password = "password";

Rebex.Licensing.Key = "Get trial key at https://www.rebex.net/support/trial/";

using var ftp = new Sftp();

ftp.FingerprintCheck += (sender, e) => {
var knownHostsStore = new Demo.ServerIdentity.KnownHostsStore();
var verificationResult = knownHostsStore.VerifyHost(ServerName, e.ServerKey);
e.Accept = verificationResult == Demo.ServerIdentity.HostVerificationResult.Success;
};

Console.Write("Connecting to SFTP server...");
await ftp.ConnectAsync(ServerName);
Console.WriteLine("OK");

Console.Write($"Logging in user {UserName}...");
await ftp.LoginAsync(UserName, Password);
Console.WriteLine("OK");

Console.Write("Disconnecting...");
await ftp.DisconnectAsync();
Console.WriteLine("OK");

Run the program. It will end with an exception, because the key was rejected:

Connecting to SFTP server...Unhandled exception. Rebex.Net.SftpException: Negotiation failed. The server key was rejected by the client.
---> Rebex.Net.SshException: The server key was rejected by the client.
at Rebex.Net.SshSession.wiqaz(SshPublicKey p0)
at Rebex.Net.SshSession.byljs(Byte[] p0)
at Rebex.Net.SshSession.Negotiate()
at Rebex.Net.Sftp.yqzns.jjxfu(ikhyu p0, Boolean p1)
at Rebex.Net.Sftp.gdmsk(String p0, Int32 p1, SshParameters p2, ikhyu p3)
--- End of inner exception stack trace ---
at Rebex.Net.Sftp.gdmsk(String p0, Int32 p1, SshParameters p2, ikhyu p3)
at Rebex.Net.Sftp.ccuqz(Object p0, Enum p1, Object[] p2)
at isowr.ppimo.ctegf(Object p0)
--- End of stack trace from previous location ---
at Program.<Main>$(String[] args) in X:\Repos\RebexArticles\Demo.ServerIdentity\Program.cs:line 18
at Program.<Main>(String[] args)