Connecting
SshClient is one authenticated SSH connection. Every way of connecting returns it after the key exchange and
authentication have succeeded; dispose it to disconnect. Architecture and connection lifecycle shows
the handshake step by step.
Over TCP
await using var client = await SshClient.ConnectAsync("example.com", 22, new SshClientOptions
{
UserName = "deploy",
Password = password,
HostKeyVerifier = KnownHostsVerifier.ForCurrentUser(StrictHostKeyChecking.Yes),
});
Socket errors surface as SshException with SshFailureReason.ConnectFailed.
Connect timeout
ConnectTimeout bounds the whole attempt: name resolution, the TCP connection (or the proxy), the key exchange, host key
verification and authentication. When it passes, the attempt fails with SshException and SshFailureReason.Timeout; cancelling
your token is still an OperationCanceledException. It is null (no limit) by default.
try
{
await using var client = await SshClient.ConnectAsync("example.com", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = await LoadKeysAsync(cancellationToken),
HostKeyVerifier = verifier,
ConnectTimeout = TimeSpan.FromSeconds(15), // TCP, key exchange and authentication together
}, cancellationToken);
}
catch (SshException ex) when (ex.Reason == SshFailureReason.Timeout)
{
Console.WriteLine($"Gave up: {ex.Message}"); // the caller cancelling is an OperationCanceledException instead
}
Over a stream it bounds the key exchange and authentication. See Cancellation and timeouts.
IPv4 or IPv6 only
AddressFamily chooses which of the server's addresses are tried, as ssh -4 and ssh -6 (AddressFamily inet and inet6 in
ssh_config) do: Any (the default), Inet (IPv4) or Inet6 (IPv6).
// Only the server's IPv4 addresses are tried (ssh -4, AddressFamily inet): for a network whose IPv6 route is broken.
await using var client = await SshClient.ConnectAsync("example.com", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = keys,
HostKeyVerifier = verifier,
AddressFamily = SshAddressFamily.Inet, // or Inet6; Any (the default) tries every address
ConnectTimeout = TimeSpan.FromSeconds(15),
}, cancellationToken);
An address literal of the other family, or a name with no address of the allowed one, fails with ConnectFailed. Through a Proxy
it does not apply, since the proxy resolves the name. With LocalEndPoint, both restrictions apply.
A name's addresses are tried in the order the system's resolver returns them, each with a new socket of its family, until one
connects. Socket options set by ConfigureSocket or ssh_config's IPQoS are set again on each one. When none connects, the
error of the last is reported.
Race the server's addresses
An address that does not answer at all (a broken IPv6 route, a firewall that drops rather than refuses) holds up the addresses after
it until the system gives up on it, which can take minutes, or until ConnectTimeout ends the whole attempt. AddressFamily avoids
that where you know which family is broken. StaggeredConnectDelay avoids it without knowing: the addresses are raced, as RFC 8305
("Happy Eyeballs") describes.
// The server's addresses are raced, RFC 8305 style: each has 250 ms to connect before the next is tried too, and the first
// connection made is used. A broken IPv6 route then costs 250 ms, not the system's connect timeout.
await using var client = await SshClient.ConnectAsync("example.com", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = keys,
HostKeyVerifier = verifier,
StaggeredConnectDelay = TimeSpan.FromMilliseconds(250), // RFC 8305's recommendation; null (the default) tries them in order
ConnectTimeout = TimeSpan.FromSeconds(15),
}, cancellationToken);
The first address is tried as usual. When it has not connected within the delay, the next is tried as well, without stopping the first, and so on; when one fails, the next starts at once. The first to connect is used and the others are closed. IPv6 and IPv4 addresses take turns, starting with the family the resolver put first:
sequenceDiagram
participant C as SshSharp
participant V6 as 2001:db8::10 (no answer)
participant V4 as 192.0.2.10
C->>V6: connect
Note over C: 250 ms, no answer
C->>V4: connect
V4-->>C: connected
C-xV6: closed
C->>V4: SSH handshake
- It is off by default (null), and the addresses are then tried one after another, as
sshdoes. RFC 8305 recommends 250 ms; the delay must be from 10 ms to 2 s. - There is nothing to race for an IP address or a name with one address, nor through a
Proxy, which resolves the name itself. WithJumpHosts, it applies to the connection to the first hop. AddressFamilyandLocalEndPointstill decide which addresses take part, andConnectTimeoutbounds the race. Each retry thatConnectionAttemptsmakes races the addresses again.ConfigureSocketis called once for each socket, before it connects, one socket at a time. A server may log the connections that lost as closed before the SSH handshake.- The name is resolved once, by the system's resolver; SshSharp does not query IPv6 and IPv4 addresses separately.
SshConfigConnectOptions.StaggeredConnectDelaydoes the same when connecting by alias.ssh_confighas no directive for it.
Over any stream
SSH can run over anything duplex: a WebSocket wrapper, a named pipe, a tunnel of your own. Without a host name there is
nothing to look up in known_hosts, so give one with HostKeyAlias (or pin the key).
Stream transport = await OpenMyTransportAsync();
await using var client = await SshClient.ConnectAsync(transport, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = [key],
HostKeyAlias = "build-agent-7",
HostKeyVerifier = KnownHostsVerifier.ForCurrentUser(StrictHostKeyChecking.Yes),
}, leaveOpen: false);
By ssh_config alias
SshClient.ConnectAsync(destination, options) resolves the destination like ssh does. The destination is an alias or host,
optionally user@host, or ssh://user@host:port.
await using var client = await SshClient.ConnectAsync("deploy@prod-db", new SshConfigConnectOptions
{
// Optional. Asked for the passphrase of an encrypted IdentityFile (not in BatchMode).
PassphraseProvider = (path, ct) => ValueTask.FromResult<string?>(Prompt($"Passphrase for {Path.GetFileName(path)}: ")),
// Optional. Asked about unknown host keys under StrictHostKeyChecking ask.
AskHostKey = (prompt, ct) => ValueTask.FromResult(Confirm($"Trust {prompt.Context.HostKey.Fingerprint}?")),
});
What is taken from the configuration: HostName, Port, User, IdentityFile, CertificateFile, IdentityAgent,
IdentitiesOnly, UserKnownHostsFile, GlobalKnownHostsFile, RevokedHostKeys, StrictHostKeyChecking, HashKnownHosts,
UpdateHostKeys, HostKeyAlias, KexAlgorithms, HostKeyAlgorithms, Ciphers, MACs, PubkeyAcceptedAlgorithms (which
keys are offered, and how RSA keys sign; one that allows nothing SshSharp uses, such as PubkeyAcceptedKeyTypes ssh-rsa, offers
no key but leaves passwords working), RequiredRSASize, CASignatureAlgorithms, PreferredAuthentications, PubkeyAuthentication, PasswordAuthentication, KbdInteractiveAuthentication,
NumberOfPasswordPrompts, BatchMode, ProxyJump, ProxyCommand, ServerAliveInterval, ServerAliveCountMax,
ConnectTimeout, ConnectionAttempts, AddressFamily, BindAddress, BindInterface, TCPKeepAlive, IPQoS, Compression, ForwardAgent,
AddKeysToAgent (ask with ConfirmAddKeyToAgent), GSSAPIAuthentication, GSSAPIDelegateCredentials, ChannelTimeout,
ObscureKeystrokeTiming, RefuseConnection and KnownHostsCommand (with AllowKnownHostsCommand); with StartForwardings,
also LocalForward, RemoteForward, DynamicForward, PermitRemoteOpen, GatewayPorts, StreamLocalBindMask,
StreamLocalBindUnlink, ExitOnForwardFailure and ClearAllForwardings. CanonicalizeHostname and the other Canonicalize*
directives apply when ResolveOptions turns on UseDnsCanonicalizer or sets a HostCanonicalizer. Match (including
Match exec, which needs an opt-in) and Include work as in OpenSSH.
SshConfigConnectOptions also takes a Config (default: the user's and the system's files), ResolveOptions (home
directory, environment, local user, host name canonicalization), a Password or PasswordProvider, ChangePassword, extra
PrivateKeys (the destination's, offered before its identity files), a PassphraseProvider for encrypted identity files, KeyboardInteractive, a HostKeyVerifier that replaces the
configured one, AskHostKey and ConfirmHostKeyUpdate, ConfirmAddKeyToAgent (for AddKeysToAgent ask), UseAgent/Agent,
ForwardAgentFilter, AllowProxyCommand, AllowKnownHostsCommand, a Proxy (HTTP or SOCKS), ConfigureSocket (run after
TCPKeepAlive and IPQoS), StartForwardings, AuthenticationBanner and a Logger. Port, ConnectTimeout,
ConnectionAttempts, AddressFamily, KeepAliveInterval, KeepAliveCountMax and Compression override what the configuration says, and
StaggeredConnectDelay races the addresses, which ssh_config cannot ask for (see
Override what the configuration says).
Jump hosts and proxy commands
ProxyJump a,b connects to a, then to b through a, then to the target through b; each hop is verified and
authenticated with its own configuration: its identity files and the agent. What the caller gives in SshConfigConnectOptions
(Password, PasswordProvider, KeyboardInteractive, ChangePassword and PrivateKeys) is the destination's and never reaches
a hop. (Before 1.1, PrivateKeys were offered to every hop too.) A hop that refuses to log in fails with "Authentication to
ProxyJump hop N failed" (an SshAuthenticationException wrapping the hop's own), so it is not mistaken for the destination's
refusal. ProxyCommand runs a local command and speaks SSH over its standard input and
output, as ssh does; set AllowProxyCommand = false to refuse configurations that name one.
Without ssh_config, SshClientOptions.JumpHosts builds the same chain: a list of SshJumpHost, each with its own host, port and
SshClientOptions (user, credentials, host key verifier). The destination's credentials are never offered to a hop, its
ConnectTimeout bounds the whole chain, and disposing the client closes every hop:
// The destination: its own user, key and host key check, which the bastion is never offered.
await using var client = await SshClient.ConnectAsync("app1.internal", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = [deployKey],
HostKeyVerifier = new KnownHostsVerifier([Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".ssh", "known_hosts")]),
ConnectTimeout = TimeSpan.FromSeconds(30), // the whole chain: every hop and the destination
// First to last: each hop logs in and is verified with its own options.
JumpHosts =
[
new SshJumpHost("bastion.example.com", 22, new SshClientOptions
{
UserName = "jump",
PrivateKeys = [bastionKey],
HostKeyVerifier = SshHostKeyVerifier.Pinned(bastionFingerprint),
HostKeyAlgorithms = SshAlgorithmList.Only("ssh-ed25519"), // any client option, for this hop alone
}),
],
}, cancellationToken);
var result = await client.RunCommandAsync("hostname", cancellationToken);
See Jump hosts for what applies where.
From a chosen local address
On a machine with several networks (a VPN, a management network), LocalEndPoint picks the address the connection comes from, as
ssh -b does:
var options = new SshClientOptions
{
UserName = "deploy",
PrivateKeys = [key],
HostKeyVerifier = verifier,
LocalEndPoint = new IPEndPoint(IPAddress.Parse("10.20.0.5"), 0), // port 0: any local port
};
With ssh_config, BindAddress 10.20.0.5 does the same, and BindInterface eth1 (ssh -B) uses that interface's addresses.
An IPv4 address reaches only IPv4 destinations and an IPv6 one only IPv6: the server's addresses are filtered to match, and
the error says so when none is left. The connection to a proxy is made from the same address.
Through an HTTP or SOCKS proxy
Where outbound connections must go through a proxy, set Proxy:
await using var client = await SshClient.ConnectAsync("ssh.example.com", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = [key],
HostKeyVerifier = verifier,
Proxy = SshProxy.Http("proxy.corp", 3128, new NetworkCredential("me", proxyPassword)),
});
SshProxy.Http uses CONNECT (with Basic credentials if given), SshProxy.Socks5 SOCKS 5 (with username and password
if given), and SshProxy.Socks4 SOCKS 4, or 4a for host names. SshProxy.FromUri(new Uri("socks5://user:pass@proxy:1080"))
reads the usual URI form (http, socks5, socks5h, socks4, socks4a). The server's host name is sent to the proxy, which
resolves it. A refusal, such as a 407 or a SOCKS error code, is an SshException with Reason = ConnectFailed saying what
the proxy answered. A proxy that does not finish its handshake within 30 seconds fails with Reason = Timeout. Host names must be ASCII
(use the punycode form of an internationalized name), since the proxy protocols cannot carry anything else.
With ssh_config, SshConfigConnectOptions.Proxy applies to the first network hop: the destination, or the first
ProxyJump host (later hops go through SSH). proxy.ConnectAsync(host, port) returns the proxied stream itself, for
SshClient.ConnectAsync(stream, ...) or anything else.
Basic and SOCKS 5 credentials cross the network to the proxy unencrypted, as with every client of these protocols; the SSH connection inside is encrypted end to end as usual.
Your own transport
For a transport that is neither TCP nor HTTP or SOCKS (a cloud provider's tunnel, a WebSocket, a named pipe), SshProxy.FromConnector
takes a function that returns a connected stream for a host and port. Its Type is SshProxyType.Custom. It is used wherever a
proxy is: SshClientOptions.Proxy, SshConfigConnectOptions.Proxy, and the first hop of JumpHosts or ProxyJump:
// Any transport that returns a connected stream: it is asked for the first network hop (here, the server itself).
var proxy = SshProxy.FromConnector(async (host, port, ct) => await tunnels.OpenAsync(host, port, ct));
await using var client = await SshClient.ConnectAsync("app1.internal", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = [key],
HostKeyVerifier = verifier, // the tunnel is not trusted: the server's key is checked as always
Proxy = proxy,
}, cancellationToken);
The connector's token ends with the caller's and with ConnectTimeout; there is no other time limit, and LocalEndPoint and
AddressFamily do not apply. Anything it throws becomes an SshException with Reason = ConnectFailed and the original inside,
except an SshException (passed as it is) and the caller's own cancellation. The stream belongs to the connection from then on.
The transport is not trusted: the server's host key is verified over it as over TCP. Connecting over a stream you opened yourself
(SshClient.ConnectAsync(stream, ...)) remains possible, but a custom proxy keeps the rest: ConnectTimeout covering the connection,
jump hosts behind it, the DI package's endpoints and ssh_config.
Socket options, identification and channel sizes
These options shape the connection itself. Tune and inspect a connection has the details.
ConfigureSocketis called with the TCP socket before it connects, to set TCP keep-alive, buffer sizes or the type of service. It applies to the TCP connection SshSharp opens, to the server or to the first ofJumpHosts: not through aProxy, and not over a stream you opened.SshConfigConnectOptions.ConfigureSocketdoes the same when connecting by alias, afterssh_config'sTCPKeepAlive(on unless it saysno, as inssh) andIPQoShave been applied, so what it sets wins.ConnectionAttemptstries a server that could not be reached again, one second apart, asssh_config's directive does (default 1).ConnectTimeoutbounds all the attempts together.VersionAddendumadds a comment to the client's identification line (SSH-2.0-SshSharp_1.3.0 inventory-sync/3.4), which servers log. It is sent unencrypted, so it must not hold anything secret or personal.ChannelWindowSize(default 2 MiB) andChannelMaxPacketSize(default 32 KiB) set how much the server may send on each channel before waiting, and in what packet size. A channel moves at most one window per round trip, so a larger window speeds up downloads, command output and tunnels over fast links with a long round trip:
// A fast link with a long round trip: 16 MiB in flight per channel instead of 2 MiB, in packets of up to 255 KiB.
await using var client = await SshClient.ConnectAsync("backup.example.com", 22, new SshClientOptions
{
UserName = "backup",
PrivateKeys = [await SshPrivateKey.LoadAsync("/etc/myapp/backup_ed25519", cancellationToken: cancellationToken)],
HostKeyVerifier = verifier,
ChannelWindowSize = 16 * 1024 * 1024,
ChannelMaxPacketSize = 255 * 1024,
}, cancellationToken);
await using var sftp = await client.OpenSftpAsync(cancellationToken);
await sftp.DownloadFileAsync("dumps/db.tar.zst", "db.tar.zst", cancellationToken: cancellationToken);
Tunnels and port forwarding
A tunnel is a connection the server makes on your behalf, returned as a Stream. The server resolves the host name, so it
can name machines only the server can reach.
// TCP, as ssh -L uses (direct-tcpip).
await using var database = await client.OpenTcpTunnelAsync("db.internal", 5432);
// A Unix domain socket on the server (direct-streamlocal@openssh.com), for example the Docker socket.
await using var docker = await client.OpenUnixSocketTunnelAsync("/var/run/docker.sock");
Local port forwarding (ssh -L 15432:db.internal:5432) listens locally and tunnels every connection made to it:
await using var forwarder = await client.ForwardLocalPortAsync(
new IPEndPoint(IPAddress.Loopback, 0), "db.internal", 5432); // port 0: the system picks a free one
Console.WriteLine($"Connect to {forwarder.LocalEndPoint}");
Either end can be a Unix socket, as with ssh -L:
// ssh -L 15432:/run/postgresql/.s.PGSQL.5432: a port here, a Unix socket on the server (direct-streamlocal@openssh.com).
await using var postgres = await client.ForwardLocalPortAsync(new IPEndPoint(IPAddress.Loopback, 15432), "/run/postgresql/.s.PGSQL.5432");
// ssh -L /tmp/docker.sock:/var/run/docker.sock and -L /tmp/db.sock:db.internal:5432: a Unix socket here.
await using var docker = await client.ForwardLocalUnixSocketAsync("/tmp/docker.sock", "/var/run/docker.sock");
await using var db = await client.ForwardLocalUnixSocketAsync("/tmp/db.sock", "db.internal", 5432);
A socket created here is owner-only (mode 0600, or an ACL with only the current user on Windows), is not created over an existing
file, and is removed when the forwarder is disposed. As ssh does, a connection to it is announced to the server as coming from
127.0.0.1 port 65535, since a Unix socket has no address.
Each forwarded connection gets its own channel, and a half-close travels both ways as it does with ssh. Bind to a loopback
address unless other machines should use the tunnel. Forwarding stops when the forwarder or the client is disposed, or the
connection ends. A server that does not allow forwarding (sshd's AllowTcpForwarding no) refuses each connection, and
OpenTcpTunnelAsync throws an SshException with SshFailureReason.ChannelClosed.
HttpClient through the connection
CreateHttpConnectCallback() plugs the tunnels into HttpClient, so it reaches web services only the server can reach, without
a local listener or port:
using var http = new HttpClient(new SocketsHttpHandler
{
ConnectCallback = client.CreateHttpConnectCallback(),
UseProxy = false, // otherwise a system proxy setting would be the destination, reached through the server
});
var health = await http.GetStringAsync("https://internal-api.corp/health");
Host names are resolved by the server, and TLS runs from here to the service as usual. The same handler works with
IHttpClientFactory (ConfigurePrimaryHttpMessageHandler).
Dynamic forwarding (ssh -D 1080) runs a SOCKS proxy: applications name their destination, and the server makes each
connection (and resolves the host names). SOCKS 4, 4a and 5 are supported, with CONNECT and no authentication.
await using var proxy = await client.ForwardDynamicPortAsync(new IPEndPoint(IPAddress.Loopback, 1080));
// for example: curl --socks5-hostname 127.0.0.1:1080 http://intranet.internal/
The proxy has no authentication, so anyone who can reach it can use the server's network: keep it on a loopback address. When
other machines must use it, pass a NetworkCredential: the proxy then takes only SOCKS 5 with username/password authentication
(RFC 1929). The password and the traffic to the proxy cross the local network in clear text, so loopback stays the better choice
where it will do; see Dynamic forwarding with a password.
Remote port forwarding (ssh -R 8080:localhost:3000) is the other direction: the server listens, and each connection made
to it is relayed to a host and port reached from this machine.
await using var remote = await client.ForwardRemotePortAsync(
"localhost", 8080, // where the server listens: "localhost" (its loopback), an address, or "" for every address
"127.0.0.1", 3000); // where its connections go, from here
Console.WriteLine($"The server forwards its port {remote.RemotePort}");
Port 0 asks the server to pick a free port (remote.RemotePort has it). Whether the server honours a bind address other than its
loopback is up to it (sshd's GatewayPorts). Disposing the forwarder cancels the forwarding on the server and closes its
connections; a connection the server forwards while nothing listens locally is closed straight away.
Remote dynamic forwarding (ssh -R 1080, OpenSSH 7.6 and later) combines the two: the server listens, and this machine
answers each connection as a SOCKS proxy (4, 4a and 5), connecting to whatever destination the server's side asks for. It gives a
remote machine outbound access through this machine's network, for example a build host reaching an internal package mirror.
await using var socks = await client.ForwardRemoteDynamicPortAsync("localhost", 1080,
allowDestination: (host, port) => host == "mirror.internal" && port == 443);
// on the server: curl --socks5-hostname localhost:1080 https://mirror.internal/
The destinations come from the server's side, so anyone who can reach the forwarded port there can use this machine's network.
Like ssh, every destination is allowed when allowDestination is null; pass a filter unless you trust everyone on the server.
The filter cannot be sidestepped by spelling: an address in any form (127.1, 0x7f.1, ::ffff:127.0.0.1, [::1]) reaches it
in canonical form (127.0.0.1, ::1), and a host name is checked as given, then resolved on this machine and each address it
resolves to is checked as well; the connection goes only to an address that passed. A filter that throws refuses that
connection. IsDynamic (socks.IsDynamic here) tells the two kinds of remote forwarding apart.
Remote forwarding can also serve the server's connections from your own code, with no local port: pass a handler instead of a
host and port. Each connection made to the forwarded port on the server arrives as an SshForwardedConnection, whose Stream
the handler reads and writes, with the address and port that were connected and the originator's, as the server reports them.
await using var remote = await client.ForwardRemotePortAsync("localhost", 8080, async (connection, ct) =>
{
// connection.Stream is this one connection; it is disposed (closed) when the handler returns
await connection.Stream.WriteAsync("hello from the client side\n"u8.ToArray(), ct);
}, maxConnections: 20);
Handlers run concurrently, one per connection. One that throws closes its own connection only (the exception is logged by type).
A handler that stops reading holds the server back at the channel window. maxConnections (100 by default) caps the connections
served at once by the forwarding, and the server's channels above it are refused. The handler's token is cancelled when the
forwarder is disposed or the connection ends; disposal cancels the forwarding on the server, cancels the handlers, waits up to
HandlerShutdownTimeout (5 seconds by default) for them, and then closes the connections of any still running.
connection.ShutdownSendAsync() ends the handler's side only (end-of-file to the program on the server), and the handler keeps
reading. ForwardRemoteUnixSocketAsync takes a handler in the same way. See
Serving a remote port from your app.
The server can open at most SshClientOptions.MaxForwardedConnections (1,000) forwarded connections at a time over all remote
forwardings and agent forwarding's agent channels; more are refused until some close.
Remote Unix-socket forwarding (ssh -R /remote/socket:target, streamlocal-forward@openssh.com, OpenSSH 6.7 and later) has
the server listen on a Unix socket instead of a port, and relays each connection to a host and port, or to a Unix socket on this
machine. It lets a program on the server use a local agent, for example gpg-agent, or a service that only this machine reaches.
// Programs on the server connect to /run/user/1000/app.sock and reach port 3000 here.
await using var app = await client.ForwardRemoteUnixSocketAsync("/run/user/1000/app.sock", "127.0.0.1", 3000);
// gpg-agent forwarding: the server's agent socket goes to this machine's extra socket.
await using var gpg = await client.ForwardRemoteUnixSocketAsync(
"/run/user/1000/gnupg/S.gpg-agent", "/run/user/1000/gnupg/S.gpg-agent.extra");
sshd creates the socket readable only by the user, and does not replace a file that is already there unless
StreamLocalBindUnlink yes is set on the server. Disposing the forwarder cancels it (cancel-streamlocal-forward@openssh.com);
client.RemoteSocketForwardings lists the ones started from ssh_config. A server with AllowStreamLocalForwarding no
refuses the request, and the call throws an SshException.
Note
Known issue on Windows: when the target is a local Unix socket, Windows sometimes fails to deliver the end of stream to the local program after SshSharp shuts down its sending side. A program that is waiting in a receive at that moment may never see it (about 1 exchange in 10,000 with plain Winsock, more often through .NET's sockets). A protocol that half-closes and then waits for the answer can stall in that case. SshSharp can do nothing about it once it has shut down its side. Protocols that frame their messages (a length or a delimiter) are not affected, and neither are TCP targets.
Forwardings from ssh_config
LocalForward, RemoteForward and DynamicForward are started when connecting by alias with
SshConfigConnectOptions.StartForwardings = true (off by default: they open listening ports). They are disposed with the
client, and client.LocalForwardings, RemoteForwardings and DynamicForwardings list them. RemoteForward with just a
port (RemoteForward 1080) is remote dynamic forwarding, with every destination allowed, as in ssh, unless PermitRemoteOpen lists
the ones allowed (host:port entries, * for any host or port, or none; names are compared as given, without lookups). RemoteForward with a
socket path (RemoteForward /run/app.sock 127.0.0.1:3000 or RemoteForward /remote.sock /local.sock) is remote Unix-socket
forwarding, listed in client.RemoteSocketForwardings; as in ssh, a target with a / in it is a socket path. LocalForward takes
socket paths on either side: LocalForward /tmp/docker.sock /var/run/docker.sock, LocalForward 15432 /run/postgresql/.s.PGSQL.5432
or LocalForward ~/db.sock db.internal:5432. Those that listen on a socket here are listed in client.LocalSocketForwardings, each an SshLocalSocketForwarder with its LocalSocketPath, its RemoteHost and RemotePort or RemoteSocketPath, and ActiveConnections. Their paths
take ssh_config's tokens (%d, %h, %C and the rest) and ${VAR}, as ssh expands them, and a local path ~ too (a
path on the server never does); a local path may also be written with \ on Windows, in RemoteForward too. StreamLocalBindUnlink yes replaces a stale socket file instead of failing, and StreamLocalBindMask
sets the socket file's permissions (0177, owner-only, by default; 0117 lets the owner's group connect). RemoteForward socket
paths take the tokens and ${VAR} too, expanded on this machine as ssh does (RemoteForward /home/%r/app.sock /run/app.sock:
%r is the remote user); ~ only in the local one, since on the server's side it would name this machine's home directory.
Host db-tunnel
HostName bastion.example.com
LocalForward 15432 db.internal:5432
DynamicForward 1080
ExitOnForwardFailure yes
Bind addresses follow ssh: none means loopback (every address with GatewayPorts yes), localhost loopback, * every
address. A forwarding that cannot be set up (a port or socket file in use, refused by the server) is logged and skipped, or fails
the connection with ExitOnForwardFailure yes. ClearAllForwardings yes starts none.
Keep-alive and connection state
var options = new SshClientOptions
{
UserName = "deploy",
Password = password,
HostKeyVerifier = verifier,
KeepAliveInterval = TimeSpan.FromSeconds(30), // ServerAliveInterval; null or TimeSpan.Zero sends none
KeepAliveCountMax = 3, // ServerAliveCountMax
};
await using var client = await SshClient.ConnectAsync("example.com", 22, options);
// Cancelled when the connection ends for any reason; ConnectionError says why.
client.ConnectionClosed.Register(() => Console.WriteLine($"Disconnected: {client.ConnectionError?.Message}"));
IsConnected turns false once the server disconnects, the connection fails (including missed keep-alives) or the client
is disposed.
The client also describes the connection: RemoteEndPoint and LocalEndPoint (when it runs over a socket), ConnectedAt, the
SessionId, and the BytesSent and BytesReceived so far. RekeyAsync() renews the keys on demand, as ssh's ~R escape does;
they are renewed on their own after RekeyAfterBytes (1 GiB) or RekeyAfterTime (1 hour) anyway:
Console.WriteLine($"server: {client.ServerIdentification}"); // SSH-2.0-OpenSSH_9.9
Console.WriteLine($"remote: {client.RemoteEndPoint}"); // 192.0.2.10:22 (null over a stream that is no socket)
Console.WriteLine($"local: {client.LocalEndPoint}"); // 198.51.100.7:50514
Console.WriteLine($"connected: {client.ConnectedAt:u} ({DateTimeOffset.UtcNow - client.ConnectedAt:hh\\:mm\\:ss} ago)");
Console.WriteLine($"session id: {Convert.ToHexString(client.SessionId.Span)}");
Console.WriteLine($"traffic: {client.BytesSent:N0} bytes sent, {client.BytesReceived:N0} received");
Console.WriteLine($"cipher: {client.Algorithms.EncryptionClientToServer}");
Console.WriteLine($"compressed: {client.Algorithms.CompressionServerToClient}"); // zlib@openssh.com, or none
Keep-alive probes are OpenSSH transport pings (ping@openssh.com) where the server announces them (OpenSSH 9.5 and later), and
keepalive@openssh.com requests otherwise, as OpenSSH's client sends. Any packet from the server counts as an answer.
client.PingAsync() measures a round trip the same way, and also proves the connection is alive:
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); // otherwise a silent server is waited for until the connection ends
var roundTrip = await client.PingAsync(cts.Token);
Console.WriteLine($"{roundTrip.TotalMilliseconds:F1} ms");
Warning
OpenSSH for Windows: the server built into Windows (OpenSSH for Windows 9.5) often fails to answer keep-alives, and the
connection then ends after KeepAliveCountMax intervals, as it does with OpenSSH's own ssh -o ServerAliveInterval. It announces
ping@openssh.com, so SshSharp probes it with pings, but those go unanswered at times too: the server stops sending on the
connection. Against it, leave KeepAliveInterval unset or use a long interval with a generous KeepAliveCountMax.
Channel idle timeouts
ChannelTimeouts closes channels that carry no data for a while, by channel type, as OpenSSH's ChannelTimeout (9.2 and later)
does on the client side. The first entry whose type pattern matches applies; a zero timeout means none for that type:
var options = new SshClientOptions
{
// ...
ChannelTimeouts =
[
new SshChannelTimeout("session", TimeSpan.Zero), // shells and commands: never
new SshChannelTimeout("direct-*", TimeSpan.FromMinutes(10)), // local forwardings and tunnels
new SshChannelTimeout("*", TimeSpan.FromHours(1)), // everything else
],
};
The types are session, direct-tcpip, direct-streamlocal@openssh.com, forwarded-tcpip, forwarded-streamlocal@openssh.com
and agent-connection (patterns such as direct-* and * work; names are case-sensitive). OpenSSH's x11-connection and
tun-connection are accepted but never match: SshSharp has no X11 or tunnel-device forwarding, so it has no such channels.
Data sent or received in either direction resets a channel's clock. An idle channel is closed with an ordinary channel close: the
connection stays up, a session's output streams end, and a forwarded connection's local socket is closed. In ssh_config, write
ChannelTimeout session=0 direct-*=10m *=1h (none turns it off); connecting by alias applies it.
Algorithms
The defaults prefer modern algorithms: the post-quantum hybrid mlkem768x25519-sha256 (in OpenSSH since 9.9 and its default since 10.0; offered on
.NET 10 and later where the platform has ML-KEM: OpenSSL 3.5+ or a recent Windows), followed by the RFC 10042 hybrids with NIST curves,
mlkem768nistp256-sha256 and mlkem1024nistp384-sha384, then sntrup761x25519-sha512 (and its older name
sntrup761x25519-sha512@openssh.com; managed, so offered on every platform and on .NET 8, and the only post-quantum method of
OpenSSH 8.5 to 9.8, for example Ubuntu 24.04's 9.6), then curve25519-sha256 and ecdh-sha2-nistp* (plus
the finite-field diffie-hellman-group-exchange-sha256 and diffie-hellman-group16/18/14, last, as OpenSSH orders them) for
key exchange; chacha20-poly1305@openssh.com, aes*-gcm@openssh.com and aes*-ctr with hmac-sha2-*-etm for
ciphers, then aes*-ctr with the plain hmac-sha2-256 and hmac-sha2-512 for servers, often network equipment, that offer no
-etm MAC; ssh-ed25519, ecdsa-sha2-* and rsa-sha2-256/512 host keys, and OpenSSH host certificates. Strict key exchange
(the Terrapin fix) is always on. FipsMode = true limits negotiation to FIPS-approved algorithms, led by the two NIST-curve ML-KEM hybrids,
so FIPS mode keeps a post-quantum key exchange where the server offers one. Keys are renewed after
RekeyAfterBytes (default 1 GiB, counted in message bytes before compression) or RekeyAfterTime (default 1 hour), once the user
is authenticated, as in OpenSSH (a limit reached during authentication renews the keys right after it).
Compression is off by default, as in ssh; Compression = true offers OpenSSH's delayed zlib@openssh.com, for slow links (see
Compress a slow link).
To change the lists, set KexAlgorithms, HostKeyAlgorithms, Ciphers or Macs to an SshAlgorithmList, in the forms of
ssh_config's directives of the same names: SshAlgorithmList.Remove("diffie-hellman-*") drops from the defaults, Prepend moves
to the front, Append adds at the end (leaving one that is already a default in place, as + does), and Only replaces them.
FipsMode still applies on top. PubkeyAcceptedAlgorithms decides which of PrivateKeys are offered and the signature algorithm
an RSA key uses. RequiredRsaSize sets the
smallest RSA host key accepted (2048 bits by default). CASignatureAlgorithms narrows the signature algorithms a certificate
authority may have signed a host certificate with. See
Choose algorithms and authentication methods.
var options = new SshClientOptions
{
UserName = "deploy",
PrivateKeys = [key],
HostKeyVerifier = verifier,
KexAlgorithms = SshAlgorithmList.Remove("diffie-hellman-*"),
Ciphers = SshAlgorithmList.Prepend("aes128-gcm@openssh.com"),
};
client.Algorithms shows what a connection negotiated: key exchange, host key algorithm, ciphers and MACs (empty for AEAD
ciphers), and whether strict key exchange is on. client.Algorithms.IsPostQuantum tells whether the key exchange resists a
future quantum computer. When it does not, the client logs it at Information level, the counterpart of OpenSSH 10.1's
WarnWeakCrypto, and traces and the connect-duration metric carry ssh.kex.post_quantum, so the hosts that still negotiate
a classical key exchange are easy to find:
if (!client.Algorithms.IsPostQuantum)
{
Console.WriteLine($"{host} uses {client.Algorithms.KeyExchange}; upgrade it to OpenSSH 8.5 or later for post-quantum key exchange.");
}
Algorithms lists every algorithm, its order and whether FIPS mode keeps it.