Use ssh_config and known_hosts
SshSharp reads OpenSSH's ssh_config and known_hosts with the same semantics as ssh. Connecting by alias applies everything
the configuration says; the SshSharp.Config types also read the files directly, for tools that only want the values.
When to use
- Your users already have working
~/.ssh/configentries, and your tool should behave likesshwith them. - Operations teams manage host names, users, keys, bastions and host key policy in configuration, not in code.
- You need to inspect or update
known_hostsyourself.
Connect by alias
// Everything comes from ~/.ssh/config: HostName, User, IdentityFile, ProxyJump, known_hosts, ...
await using var client = await SshClient.ConnectAsync("prod-db", cancellationToken: cancellationToken);
// The other destination forms ssh accepts.
await using var other = await SshClient.ConnectAsync("deploy@build.example.com", cancellationToken: cancellationToken);
await using var third = await SshClient.ConnectAsync("ssh://deploy@build.example.com:2222", cancellationToken: cancellationToken);
What the configuration decides: HostName, Port, User, IdentityFile, CertificateFile, the agent (IdentityAgent,
IdentitiesOnly), known_hosts files and StrictHostKeyChecking, algorithms, ProxyJump and ProxyCommand, keep-alive,
ConnectTimeout, and more; the ssh_config reference lists every directive and how it is used.
Supply what a configuration file cannot
Passphrases, answers to prompts, and policy for things a file should not decide alone go in SshConfigConnectOptions:
await using var client = await SshClient.ConnectAsync("prod-db", new SshConfigConnectOptions
{
// Encrypted IdentityFile keys: the passphrase from a secret store or the environment, never from source code.
PassphraseProvider = (path, ct) =>
ValueTask.FromResult(Environment.GetEnvironmentVariable("SSH_KEY_PASSPHRASE")),
// StrictHostKeyChecking ask: decide about an unknown host key.
AskHostKey = (prompt, ct) =>
ValueTask.FromResult(Confirm($"Trust {prompt.Context.HostKey.KeyType} {prompt.Context.HostKey.Fingerprint}?")),
// A configuration that names a ProxyCommand runs a local program: refuse it unless the file is trusted.
AllowProxyCommand = false,
}, cancellationToken);
Override what the configuration says
Some transport settings belong to the application rather than to the file: a port from its own settings, a timeout that fits its
work, retries for a server that may be restarting. Set them in SshConfigConnectOptions and they win over ssh_config, as
ssh -p and ssh -o do; everything else still comes from the configuration:
// ssh_config decides the rest; these win over what it says, as ssh -p and ssh -o do.
await using var client = await SshClient.ConnectAsync("prod-db", new SshConfigConnectOptions
{
Port = 2222, // the destination's port (ssh -p); not a ProxyJump hop's
ConnectTimeout = TimeSpan.FromSeconds(15), // per host, from loading keys through authentication
ConnectionAttempts = 3, // try an unreachable server again, one second apart
AddressFamily = SshAddressFamily.Inet, // IPv4 only, for the connection this machine makes
KeepAliveInterval = TimeSpan.FromSeconds(30), // TimeSpan.Zero turns keep-alives off
KeepAliveCountMax = 4,
}, cancellationToken);
Portis the destination's, never aProxyJumphop's, and resolution sees it (%p,Match). A port written in anssh://host:portdestination still wins.ConnectTimeout,ConnectionAttemptsand the keep-alive settings apply to the destination and everyProxyJumphop.Timeout.InfiniteTimeSpanremoves the time limit andKeepAliveInterval = TimeSpan.Zero(orTimeout.InfiniteTimeSpan, asSshClientOptionstakes it) the keep-alives, whatever the file says.- An algorithm directive that leaves nothing SshSharp implements (
Ciphers aes128-cbc:sshstill has CBC, SshSharp does not) fails right after the file is read, before anything is sent, naming the directive.PubkeyAcceptedKeyTypes ssh-rsa(SHA-1 only) is the exception: no key is offered, a warning says why, and a password still logs in. AddressFamilyapplies to the one TCP connection this machine makes: to the destination, or to the firstProxyJumphop. So doesStaggeredConnectDelay, which races that connection's addresses (see Race the server's addresses);ssh_confighas no directive for it.Compressionis the destination's, asssh -C:trueorfalsewins over itsCompressionline, and eachProxyJumphop keeps its own (see Compress a slow link).ConnectionAttemptstries again only when the server could not be reached (refused, unreachable, timed out), one second apart, within the sameConnectTimeout; a host key or authentication failure is never retried.ConfigureSocketsets socket options on that same connection afterTCPKeepAliveandIPQoShave been applied, so what it sets wins (seeTCPKeepAliveandIPQoS).
Ship a configuration with your application
SshConfig.Parse (or SshConfig.Load for a file) gives the application its own configuration, independent of the user's:
// A configuration that ships with the application, instead of the user's ~/.ssh/config.
var config = SshConfig.Parse("""
Host bastion
HostName bastion.example.com
User jump
IdentityFile ~/.ssh/fleet_ed25519
Host app-*
ProxyJump bastion
User deploy
IdentityFile ~/.ssh/fleet_ed25519
UserKnownHostsFile /etc/myapp/known_hosts
StrictHostKeyChecking yes
ServerAliveInterval 30
""");
await using var client = await SshClient.ConnectAsync("app-3", new SshConfigConnectOptions { Config = config }, cancellationToken);
Read the configuration without connecting
Resolve returns what ssh -G would print for a host: Host and Match blocks, Include, tokens and environment variables
applied.
var config = SshConfig.LoadDefault(); // ~/.ssh/config, then the system-wide file
SshHostConfig host = config.Resolve("prod-db"); // what ssh -G prod-db prints
Console.WriteLine($"{host.User}@{host.HostName}:{host.Port}");
Console.WriteLine($"via {string.Join(" -> ", host.ProxyJump)}");
Console.WriteLine($"keys {string.Join(", ", host.IdentityFiles)}");
Console.WriteLine($"StrictHostKeyChecking {host.StrictHostKeyChecking}");
The verifier ssh would use for that host comes from the same resolution:
// The verifier ssh would use for this host: its known_hosts files, StrictHostKeyChecking, HashKnownHosts, RevokedHostKeys ...
var host = SshConfig.LoadDefault().Resolve("prod-db");
var verifier = KnownHostsVerifier.FromConfig(host);
Canonicalize host names
CanonicalizeHostname yes turns a short name into a fully qualified one before connecting: ssh web becomes
web.corp.example.com, and Host blocks written for full names apply. Turn on the built-in DNS canonicalizer with
SshConfigResolveOptions.UseDnsCanonicalizer:
// ~/.ssh/config:
// CanonicalizeHostname yes
// CanonicalDomains corp.example.com example.com
// CanonicalizePermittedCNAMEs *.corp.example.com:*.lb.example.net
// Host *.corp.example.com
// User deploy
//
// "ssh web" looks up web.corp.example.com., then web.example.com., and connects to the first that resolves; the Host block
// for it applies, as the configuration is read again for the canonical name.
await using var client = await SshClient.ConnectAsync("web", new SshConfigConnectOptions
{
ResolveOptions = new SshConfigResolveOptions { UseDnsCanonicalizer = true },
}, cancellationToken);
// Without connecting: ResolveAsync, since the lookups are asynchronous.
var host = await SshConfig.LoadDefault().ResolveAsync("web", new SshConfigResolveOptions { UseDnsCanonicalizer = true }, cancellationToken);
Console.WriteLine(host.HostName); // web.corp.example.com
- It follows
ssh.CanonicalDomainsare tried in order, each as an absolute name (web.corp.example.com., so the system's search list does not apply), andnoneamong them stops the list. A name with more dots thanCanonicalizeMaxDots(default 1), a name ending in a dot (looked up as it is), and an IP address are handled assshhandles them.CanonicalizeFallbackLocal nofails when nothing is found. ThroughProxyJumporProxyCommand, onlyCanonicalizeHostname alwayscanonicalizes. - CNAMEs are followed only when
CanonicalizePermittedCNAMEsallows the pair, as inssh: a found name becomes its CNAME target if a rule's source domains match the name and its target domains match the target. - Limits. The lookups use the system resolver (
System.Net.Dns): the hosts file and DNS, asgetaddrinfodoes forssh. It reports the end of a CNAME chain, not the names in between, so rules are checked against the final target. When the platform reports no canonical name, there is nothing for a rule to act on and the name stays as found.CanonicalizePermittedCNAMEswithCanonicalizeHostname nodoes not follow CNAMEs (sshdoes). - Off by default. Resolving then makes DNS queries, which the application should choose.
ResolvethrowsNotSupportedExceptionwhen lookups are needed; useResolveAsync, as connecting by alias does.HostCanonicalizerstill replaces the built-in one, for a resolver of your own.
Read and update known_hosts
var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".ssh", "known_hosts");
var knownHosts = await KnownHostsFile.LoadAsync(path, cancellationToken);
var key = client.HostKey.GetPublicKey();
switch (knownHosts.Check("example.com", 22, key))
{
case KnownHostsCheckResult.Match:
Console.WriteLine("known");
break;
case KnownHostsCheckResult.Unknown:
await KnownHostsFile.AppendAsync(path, "example.com", 22, key, hash: true, cancellationToken: cancellationToken);
break;
case KnownHostsCheckResult.Changed or KnownHostsCheckResult.Revoked:
throw new InvalidOperationException("The host key does not match known_hosts.");
}
Hashed host names (|1|salt|hash), [host]:port, wildcards and negation, @cert-authority and @revoked are understood.
AppendAsync only appends, so comments and the order of existing lines are kept.
Notes and pitfalls
- Commands in configuration files.
ProxyCommandruns a local program (allowed by default, as inssh; turn it off withAllowProxyCommand = false).KnownHostsCommanddecides which host keys are trusted, so it runs only withAllowKnownHostsCommand = true.Match execruns only whenSshConfigResolveOptions.ExecMatcheris set. Only enable these for configuration files you trust. Match execand canonicalization are asynchronous (HostCanonicalizer, or the DNS lookups ofUseDnsCanonicalizer). A configuration that needs them must be resolved withResolveAsync;ResolvethrowsNotSupportedException. Connecting by alias always resolves asynchronously.BatchMode yesturns off every prompt:AskHostKey,ConfirmHostKeyUpdate,PassphraseProviderand the keyboard-interactive handler are not used.- Session settings are yours to apply.
SendEnv,SetEnvandRequestTTYare resolved (SshHostConfig.SendEnv,SetEnv,RequestTty) but not applied by connecting, since sessions are started by your code: pass them inSshSessionOptions. - Which file.
SshConfig.LoadDefault()reads~/.ssh/config, then the system file;SshConfigConnectOptions.Configreplaces both.
See also
- Configuration files (in-depth:
Matchcriteria,KnownHostsCommand, tokens) - Connecting: by ssh_config alias
- ssh_config directives
- Verify host keys