Jump hosts (ProxyJump)
Servers inside a private network are often reachable only through a bastion (jump host). SshSharp follows ssh_config's
ProxyJump and ProxyCommand like ssh does. Without ssh_config, SshClientOptions.JumpHosts builds the same chain in code,
and it can also be done by hand: open a tunnel through one connection and run a second SSH connection over it.
When to use
- The target is not reachable directly, only through one or more bastions.
- You want each hop authenticated and verified on its own, with the bastion unable to read the traffic to the target.
How a ProxyJump chain connects
With ProxyJump bastion (or ssh -J bastion app1), the client connects and logs in to the bastion, asks it for a TCP connection to
the target's SSH port (a direct-tcpip channel), and runs a complete second SSH connection over that channel. The bastion relays
bytes it cannot decrypt; the target's host key is verified against known_hosts as for a direct connection.
sequenceDiagram
autonumber
participant C as SshSharp
participant B as bastion.example.com
participant T as app1.internal
C->>B: TCP, key exchange, host key check, login (bastion's own config)
C->>B: open direct-tcpip channel to app1.internal:22
B->>T: TCP connect
rect rgba(127, 127, 127, 0.15)
Note over C,T: second SSH connection, end to end through the channel
C->>T: key exchange, host key check (known_hosts entry for app1.internal)
C->>T: login (app1's own config and keys)
end
C->>T: commands, SFTP, forwarding ...
ProxyJump a,b repeats this: b is reached through a, and the target through b. Each hop is resolved, verified and
authenticated with its own ssh_config settings, and each hop's ConnectTimeout applies to it.
From ssh_config
Host bastion
HostName bastion.example.com
User jump
Host app1
HostName app1.internal
User deploy
ProxyJump bastion
// 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);
The configuration can also ship with your application instead of living in ~/.ssh/config:
// 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);
In code
SshClientOptions.JumpHosts lists the hops, first to last, as ssh -J a,b does. Each SshJumpHost names a host and port and
carries its own SshClientOptions: user, keys or password, HostKeyVerifier, algorithms, keep-alives. The options you pass to
ConnectAsync stay the destination's.
// 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);
What applies where:
| Setting | Applies to |
|---|---|
The destination's UserName, Password, PrivateKeys, KeyboardInteractive, HostKeyVerifier |
The destination only. |
A hop's UserName, credentials, HostKeyVerifier, algorithm lists, KeepAliveInterval, ForwardAgent |
That hop only. |
The destination's ConnectTimeout |
The whole chain: every hop, every tunnel, and the destination's handshake and login. |
A hop's ConnectTimeout |
That hop's connection, within the destination's limit. |
The destination's Proxy, LocalEndPoint, AddressFamily, ConfigureSocket, ConnectionAttempts |
The first network connection, which is the first hop's. |
A hop's AddressFamily, ConfigureSocket, ConnectionAttempts |
Not used: the first hop's connection takes the destination's. |
A hop's Proxy, LocalEndPoint, JumpHosts |
Not allowed: SshJumpHost throws ArgumentException. |
The destination's host name is resolved by the last hop, and each hop's by the one before it, so names that exist only inside
the private network work. A hop's host key is checked under the name and port given in its SshJumpHost, so a
KnownHostsVerifier finds it in known_hosts as it would for a direct connection.
In an ASP.NET Core application
An endpoint registered with AddSshClient takes its jump hosts as settings (JumpHosts), each with its own user, credentials and
host key settings, so they can come from appsettings.json with no code:
services.AddSshClient("internal-app", o =>
{
o.Host = "app1.internal.example.com"; // resolved by the bastion
o.UserName = "deploy";
o.PrivateKeyFiles.Add("~/.ssh/deploy_ed25519");
o.KnownHostsFiles.Add("/etc/myapp/known_hosts"); // holds the target's key, and the bastion's (it has none of its own below)
// The bastion, with its own user and key. The endpoint's password and keys are never offered to it, nor its to the target.
o.JumpHosts.Add(new SshEndpointJumpHost
{
Host = "bastion.example.com",
UserName = "jump",
PrivateKeyFiles = ["~/.ssh/jump_ed25519"],
});
});
A hop without host key settings of its own is checked against the endpoint's KnownHostsFiles; behind an endpoint that pins
HostKeyFingerprints, each hop needs its own. See Dependency injection: jump hosts for the
configuration keys and the rules.
Through your own tunnel
When the first hop is reached through something other than TCP, HTTP or SOCKS (a cloud provider's tunnel, a WebSocket, a named
pipe), SshProxy.FromConnector makes it a proxy: the connector is asked for a stream to a host and port. It goes wherever a proxy
goes, so it carries the first JumpHosts or ProxyJump host, or the server itself:
// 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; nothing else limits it. An exception it throws fails the
connection with ConnectFailed (the exception is inside), and the stream it returns belongs to the connection, which disposes it.
See Connecting: your own transport.
By hand
Without ssh_config or JumpHosts, open a tunnel through the bastion and connect over it with SshClient.ConnectAsync(Stream, ...):
// The bastion: an ordinary connection.
await using var bastion = await SshClient.ConnectAsync("bastion.example.com", 22, new SshClientOptions
{
UserName = "jump",
PrivateKeys = [key],
HostKeyVerifier = verifier,
}, cancellationToken);
// A tunnel from the bastion to the target's SSH port, and a second SSH connection over it. The target's host key is
// verified as always; HostKeyAlias names it in known_hosts, since this connection has no host name of its own.
var tunnel = await bastion.OpenTcpTunnelAsync("app1.internal", 22, cancellationToken);
await using var target = await SshClient.ConnectAsync(tunnel, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = [key],
HostKeyAlias = "app1.internal",
HostKeyVerifier = verifier,
}, leaveOpen: false, cancellationToken);
var result = await target.RunCommandAsync("hostname", cancellationToken);
The connection over a stream has no host name of its own, so HostKeyAlias names the target for known_hosts lookups (or use a
pinned key).
Scan a host behind a bastion
var keys = await SshClient.ScanHostKeysAsync(
ct => new ValueTask<Stream>(bastion.OpenTcpTunnelAsync("app1.internal", 22, ct)), cancellationToken: cancellationToken);
Notes and pitfalls
- Credentials go to the destination only. When connecting by alias,
SshConfigConnectOptions.Password, the keyboard-interactive handler andSshConfigConnectOptions.PrivateKeysare offered to the final host, never to a jump host. Hops log in with their ownIdentityFiles and the agent, assshasks for each host's password separately. WithJumpHosts, each host gets only what its own options hold: a hop may have a password or keys of its own, and the destination's are never offered to it. - Upgrading from 1.0:
SshConfigConnectOptions.PrivateKeysused to be offered to every hop as well. A hop that logged in with one of them now needs that key in its ownIdentityFile(in the configuration) or in the agent (SshConfigConnectOptions.Agent, for exampleSshAgent.FromKeys(key)for a key held in the application). WithIdentitiesOnly yesfor the hop, the agent's keys are offered only when they match one of itsIdentityFilelines (by the public key in<file>.pub), so also name a file holding the key's public key there, or leaveIdentitiesOnlyoff for that hop. - Which host refused. A hop that refuses to log in fails with
SshAuthenticationException"Authentication to ProxyJump hop N failed", N being its place in theProxyJumplist; the hop's own failure is theInnerException. Without it, a hop's refusal looks like the destination's. See Troubleshooting. - Reusing one options object for a hop and the destination offers its credentials to both. Give each host its own options unless they really share a login.
- Disposal. Disposing the destination client tears down the whole chain, and a connection that fails partway closes the hops
it had opened. When chaining by hand, dispose the target before the bastion (the
await usingorder above does that).- ProxyCommand runs a local program and speaks SSH over its standard input and output. It is allowed by default, as inssh; setSshConfigConnectOptions.AllowProxyCommand = falsewhen the configuration file is not under your control. - Forwarding is the bastion's call. sshd's
AllowTcpForwarding noon the bastion refuses the tunnel, and the connection fails withConnectFailed("the jump host could not open a connection to the next host"). - A proxy for the first hop.
SshConfigConnectOptions.ProxyandSshClientOptions.Proxy(HTTP, SOCKS or your own connector) apply to the first network connection: the destination, or the firstProxyJumporJumpHostshost.
See also
- Jump host sample:
JumpHostsin code, with a certificate issued in the program - Connecting: jump hosts and proxy commands
- Threat model: jump hosts
- Use ssh_config and known_hosts
- A database through a jump host