Keys and the SSH agent
Public-key authentication is the usual way to log in to SSH servers. SshSharp loads key files, uses the keys an SSH agent holds, generates new keys, and signs with keys that never leave a TPM, smart card, HSM or cloud key service.
When to use which
| Where the key lives | Use |
|---|---|
A file (~/.ssh/id_ed25519, a .pem, a PuTTY .ppk) |
SshPrivateKey.LoadAsync |
| A secret store or CI variable | SshPrivateKey.Parse |
ssh-agent, the Windows OpenSSH agent, or Pageant (including FIDO security keys) |
SshAgent.FromEnvironmentAsync() and GetKeysAsync |
| A Windows key store, the TPM, a smart card | SshPrivateKey.FromRsa / FromECDsa with RSACng / ECDsaCng |
| A cloud KMS, an HSM, a signing service | SshPrivateKey.FromSigner with your SshKeySigner |
Any of these, served as an agent to forward (no ssh-agent running) |
SshAgent.FromKeys |
Connecting by ssh_config alias needs none of this: IdentityFile and the agent are used automatically.
Load a key file
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
using var key = await SshPrivateKey.LoadAsync(
Path.Combine(home, ".ssh", "id_ed25519"),
passphrase: Environment.GetEnvironmentVariable("SSH_KEY_PASSPHRASE"), // null for a key without one
cancellationToken);
Console.WriteLine($"{key.KeyType} {key.Fingerprint} {key.Comment}");
await using var client = await SshClient.ConnectAsync("example.com", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = [key],
HostKeyVerifier = verifier,
}, cancellationToken);
Formats: OpenSSH (BEGIN OPENSSH PRIVATE KEY, encrypted too), PKCS#8 (encrypted too), PKCS#1 and SEC1 PEM (encrypted too, the
traditional way), and PuTTY .ppk versions 2 and 3. Key types: Ed25519, ECDSA (P-256, P-384, P-521) and RSA of 2048 bits or more.
Encrypted key files
Every format can be read with its passphrase; these are the ciphers each is read with:
| Format | Made by | Ciphers read |
|---|---|---|
OpenSSH (BEGIN OPENSSH PRIVATE KEY) |
ssh-keygen (the default), ssh-keygen -Z <cipher> |
aes128/192/256-ctr, aes128/192/256-cbc, aes128/256-gcm@openssh.com, chacha20-poly1305@openssh.com; key from bcrypt_pbkdf |
PKCS#8 (BEGIN ENCRYPTED PRIVATE KEY), RSA and ECDSA |
OpenSSL 3 (openssl genpkey -aes256, openssl pkcs8), .NET |
what .NET's ImportFromEncryptedPem reads (PBES2 with AES, as OpenSSL 3 writes it) |
PKCS#1 or SEC1 with Proc-Type: 4,ENCRYPTED (BEGIN RSA PRIVATE KEY, BEGIN EC PRIVATE KEY) |
ssh-keygen -m PEM with a passphrase, OpenSSL's -traditional output, OpenSSL 1.x |
AES-128-CBC, AES-192-CBC, AES-256-CBC; key from OpenSSL's legacy EVP_BytesToKey (MD5) |
PuTTY .ppk versions 2 and 3 |
PuTTYgen | aes256-cbc |
The traditional PEM encryption is read so that such keys keep working, but its key derivation is one MD5 per guess: a stolen file is cheap to attack. Convert such a key once, to the OpenSSH format:
// A key that ssh-keygen -m PEM or OpenSSL encrypted the traditional way (Proc-Type: 4,ENCRYPTED, AES-CBC): read it, and write
// it once in the OpenSSH format, whose bcrypt_pbkdf makes guessing the passphrase far slower than the old format's one MD5.
var passphrase = Environment.GetEnvironmentVariable("KEY_PASSPHRASE") ?? throw new InvalidOperationException("KEY_PASSPHRASE is not set.");
using var key = await SshPrivateKey.LoadAsync("legacy_rsa.pem", passphrase, cancellationToken);
await key.SaveAsync("id_rsa_openssh", passphrase, cancellationToken); // and id_rsa_openssh.pub
ssh-keygen -p -f <file> does the same from the command line (it rewrites the file in the OpenSSH format).
- DES and 3DES are not read. A traditional PEM key encrypted with
DES-EDE3-CBC,DES-EDE3-CFBorDES-CBC(OpenSSL's-des3, the default of some old tools) throws aFormatExceptionthat names the cipher. Like the other legacy algorithms, they are left out by design. Re-encrypt the key withssh-keygen -p -f <file>, which reads it and writes it in the OpenSSH format with AES. - No encrypted Ed25519 in PKCS#8, and no ssh.com (
BEGIN SSH2 ENCRYPTED PRIVATE KEY) keys: convert them withssh-keygen. - A wrong passphrase is a
FormatExceptionthat says so; achacha20-poly1305@openssh.comor AES-GCM key file that was changed fails the same way, because its tag no longer matches.
Load a key from a secret
// A key kept in a secret store (here: an environment variable a CI system fills), never in a file on the build agent.
using var key = SshPrivateKey.Parse(
Environment.GetEnvironmentVariable("DEPLOY_SSH_KEY") ?? throw new InvalidOperationException("DEPLOY_SSH_KEY is not set."));
Use the SSH agent
// SSH_AUTH_SOCK, else on Windows the OpenSSH agent service, else Pageant (found without blocking a thread).
var agent = await SshAgent.FromEnvironmentAsync(cancellationToken) ?? throw new InvalidOperationException("No SSH agent is running.");
var keys = await agent.GetKeysAsync(cancellationToken); // the agent signs; the private keys never enter this process
await using var client = await SshClient.ConnectAsync("example.com", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = keys,
HostKeyVerifier = verifier,
}, cancellationToken);
FromEnvironmentAsync finds the agent as ssh does without blocking a thread: on Windows that means listing the named pipes, which
can be slow. FromEnvironment() does the same synchronously, for code that is not asynchronous. With dependency injection, set the
endpoint's UseAgent instead; see Dependency injection: the SSH agent.
Agent keys work wherever key files do, including with certificates and for signing files. FIDO security keys
(sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com) work through the agent: the agent and a touch of the key make
each signature.
Forward the agent
await using var client = await SshClient.ConnectAsync("build.example.com", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = await agent.GetKeysAsync(cancellationToken),
HostKeyVerifier = verifier,
ForwardAgent = agent, // ssh -A: git on the server can authenticate with your keys while you are connected
}, cancellationToken);
await client.RunCommandAsync("git -C /srv/app pull", cancellationToken);
Warning
While you are connected, anyone with enough rights on the server can ask your forwarded agent to sign (they cannot read the keys).
Forward only to servers you trust, and narrow what they can do: with a filter, or with
keys added with destination constraints
(SshAgentKeyConstraints.Destinations).
Serve an agent from your own keys
SshAgent.FromKeys makes an agent in your process from any keys SshSharp holds: key files, generated keys, keys in the Windows key
store, keys behind an SshKeySigner (a cloud KMS, an HSM), and keys paired with certificates. Use it wherever an SshAgent goes:
authenticate through it, and forward it, so ssh and git on the server can use keys that are in no agent process, from a container
or a service where none runs.
// An agent served by this process: no ssh-agent needed. Keys from files, generated keys, and keys behind an SshKeySigner.
using var deployKey = await SshPrivateKey.LoadAsync("deploy_ed25519", Environment.GetEnvironmentVariable("SSH_KEY_PASSPHRASE"), cancellationToken);
using var kmsKey = SshPrivateKey.FromSigner(kmsSigner, comment: "kms:deploy"); // the private key stays in the KMS
var agent = SshAgent.FromKeys(deployKey, kmsKey);
await using var client = await SshClient.ConnectAsync("build.example.com", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = await agent.GetKeysAsync(cancellationToken), // authenticate through it, as with any agent
HostKeyVerifier = verifier,
ForwardAgent = agent, // and forward it: ssh and git on the server sign through this process
}, cancellationToken);
await client.RunCommandAsync("git -C /srv/app pull", cancellationToken);
When to use it:
- Forwarding a key that is not in an agent: a KMS or HSM key, a deploy key from a secret store, a key generated for one job.
- No agent process: containers, services, CI runners.
- Authenticating only: it works, but passing the keys in
PrivateKeysdirectly does the same with less machinery.
It answers as ssh-agent does, read-only:
- It lists its keys (a key paired with a certificate twice, as
ssh-addadds it: the key, then the certificate) and signs with them. - RSA keys sign with
rsa-sha2-256orrsa-sha2-512, as the request asks; a request for SHA-1ssh-rsais refused. - Like
ssh-agent, it signs whatever data it is asked to: login requests, SSH signatures (ssh-keygen -Y sign,gitcommit signing), certificates (ssh-keygen -swith-U), and other programs' own formats, such as pam_ssh_agent_auth's challenge forsudo. A key behind anSshKeySignersees data of another form asSshSignaturePurpose.Other, and a filter can limit a forwarded agent to the purposes you know. - It binds connections to sessions (
session-bind@openssh.com) and answers RFC 9987'squery. On a connection bound for a login, it signs only that session's login request, asssh-agentdoes for destination-constrained keys. - Adding, removing and locking keys are refused (
AddKeyAsyncand the others throwSshExceptionwithAgentFailed).
IsInProcess tells such an agent from one reached through a socket or pipe, and its Path is (in-process).
Decide what a forwarded agent may do
ForwardAgentFilter sees every request that programs on the server make of the forwarded agent, an in-process one or a real one, and
decides it. It gets an SshAgentRequest:
| Member | What it is |
|---|---|
Operation |
ListKeys (asked once for each key in a listing) or Sign |
Key, Certificate |
The key (with its comment, when known), and the certificate when the agent's identity is one |
Purpose, Namespace, UserName |
For a signature: a login (with the user name it logs in as), an SSH signature (with its namespace), a certificate, or null for data of any other form |
DestinationHostKey |
The host key of the server being logged in to, when the program bound its agent connection to that session (OpenSSH 8.9 and later do), verified |
ForwardingHostKeys |
The servers the agent was forwarded through, starting with the one this client connected to |
// appServers: the host keys of the servers the bastion may log in to with your keys (from their known_hosts lines).
await using var client = await SshClient.ConnectAsync("bastion.example.com", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = await agent.GetKeysAsync(cancellationToken),
HostKeyVerifier = verifier,
ForwardAgent = agent,
ForwardAgentFilter = (request, _) => ValueTask.FromResult(request switch
{
// List every key; decide when one is used.
{ Operation: SshAgentOperation.ListKeys } => true,
// Logins onward, as deploy, to those servers only (OpenSSH 8.9 or later on the bastion reports where it logs in to).
// Never file or commit signatures, and nothing for a destination that is not known.
{ Purpose: SshSignaturePurpose.Authentication, UserName: "deploy", DestinationHostKey: { } destination }
=> appServers.Contains(destination),
_ => false,
}),
}, cancellationToken);
Data that is not a login request, an SSH signature or a certificate reaches the filter with a null Purpose. Programs sign their own
formats through agents (pam_ssh_agent_auth, for sudo through the forwarded agent), so the filter decides. To restrict a forwarded
agent to known purposes, allow only those; this policy allows logins and SSH signatures and refuses certificates and unknown data:
var options = new SshClientOptions
{
UserName = "deploy",
PrivateKeys = keys,
HostKeyVerifier = verifier,
ForwardAgent = agent,
// Logins and SSH signatures (git, ssh-keygen -Y) only. Purpose is null for data of a form SshSharp does not recognise
// (pam_ssh_agent_auth's challenge, for one): refused here, as is issuing certificates.
ForwardAgentFilter = (request, _) => ValueTask.FromResult(
request.Operation == SshAgentOperation.ListKeys
|| request.Purpose is SshSignaturePurpose.Authentication or SshSignaturePurpose.FileSignature),
};
The filter can be asynchronous, to ask the user before each signature, as ssh-add -c does:
// As ssh-add -c: each signature waits for the user. askUser is your UI (a dialog, a push notification).
var options = new SshClientOptions
{
UserName = "deploy",
PrivateKeys = await agent.GetKeysAsync(cancellationToken),
HostKeyVerifier = verifier,
ForwardAgent = agent,
ForwardAgentFilter = async (request, ct) =>
request.Operation == SshAgentOperation.ListKeys
|| await askUser(
$"Allow a {request.Purpose?.ToString() ?? "unrecognised"} signature with {request.Key.Fingerprint} ({request.Key.Comment})" +
(request.DestinationHostKey is { } destination ? $" for the server with host key {destination.Fingerprint}?" : "?"),
ct),
};
sequenceDiagram
participant P as Program on the server (ssh, git)
participant S as Server
participant C as SshClient
participant F as ForwardAgentFilter
participant A as Agent (in-process, or ssh-agent)
P->>S: agent request
S->>C: agent channel (auth-agent@openssh.com)
alt list keys
C->>A: list
A-->>C: keys
C->>F: each key (ListKeys)
F-->>C: allow or deny
C-->>P: the allowed keys
else sign
C->>F: key, purpose, user, destination (Sign)
F-->>C: allow or deny
C->>A: sign, if allowed
A-->>C: signature
C-->>P: signature, or SSH_AGENT_FAILURE
end
Listing and signing are decided separately. A key the filter refuses to list is hidden, but a public key is no secret, so a sign
request can name a key that was never listed: every signature is decided on its own. To confirm each use as ssh-add -c does, allow
every listing and decide at sign time; to hide a key from the server altogether, refuse it in both.
With a filter, the forwarded agent is read-only and narrowed, whichever agent it is:
- Requests to add, remove or lock keys are refused; they never reach a real agent.
- RSA keys never sign with SHA-1: a request without a SHA-2 flag is refused and never reaches a real agent.
- A login request on a connection bound to a session must be for that session, and a host-bound one must name its host key.
- Keys whose type
SshPublicKeydoes not read (DSA in a real agent, security-key certificates) are hidden and cannot sign. - Anything the filter throws refuses the request (logged at Warning); refused requests are logged at Information with the key's fingerprint, at most 8 a minute per connection: the rest go to Debug, with one summary when the minute ends (see Logging).
Without a filter, a real agent's connection is relayed byte for byte, as ssh -A relays it. The filter applies only to requests
that come through agent forwarding; this client's own authentication through an agent is not filtered.
Add a key to the agent
var agent = SshAgent.FromEnvironment() ?? throw new InvalidOperationException("No SSH agent is running.");
using var key = await SshPrivateKey.LoadAsync("deploy_ed25519", Environment.GetEnvironmentVariable("SSH_KEY_PASSPHRASE"), cancellationToken);
await agent.AddKeyAsync(key, new SshAgentKeyConstraints { Lifetime = TimeSpan.FromHours(1) }, cancellationToken); // ssh-add -t 1h
From ssh_config: AddKeysToAgent
When connecting by alias, AddKeysToAgent adds an identity file's key to the agent once the server has accepted it, so the next
connection signs with the agent and does not read the file (or ask for its passphrase) again:
| Value | What happens |
|---|---|
no (the default) |
Nothing is added. |
yes, or a lifetime (1h) |
The key is added, for that long when a lifetime is given (ssh-add -t). |
confirm, or confirm 1h |
The key is added with confirmation required for each use (ssh-add -c), and the lifetime if given. |
ask |
SshConfigConnectOptions.ConfirmAddKeyToAgent is asked first, for each key; the key is added (with no constraints, as ssh adds it) only when it says yes. |
With ask, ssh shows a dialog through SSH_ASKPASS; your application shows its own prompt:
// ~/.ssh/config: Host *
// AddKeysToAgent ask
// Once a server has accepted a key from an identity file, ask before it goes to the agent, as ssh asks with ssh-askpass.
await using var client = await SshClient.ConnectAsync("deploy@build", new SshConfigConnectOptions
{
ConfirmAddKeyToAgent = (prompt, ct) =>
{
Console.Write($"Add key {prompt.IdentityFile} ({prompt.Comment ?? prompt.Fingerprint}) to the agent? [y/N] ");
return ValueTask.FromResult(Console.ReadLine()?.Trim() is "y" or "Y");
},
}, cancellationToken);
- Without a way to ask, nothing is added. With no
ConfirmAddKeyToAgent, or inBatchMode,askadds no key, assshdoes when it cannot ask. - The prompt carries the identity file's path, the key's fingerprint and comment, and the host that accepted it. It is asked
after the connection is made: your
CancellationTokenbounds it, notConnectTimeout. What it throws closes the new connection and is thrown fromConnectAsync. - Only identity-file keys. Keys you pass in
SshConfigConnectOptions.PrivateKeys, and keys the agent already holds, are never added, and an agent that is not running is logged and skipped. AProxyJumphop applies its ownAddKeysToAgent.
Generate a key
using var key = SshPrivateKey.Generate(SshKeyType.Ed25519, comment: "ci-deploy");
await key.SaveAsync("ci_ed25519", Environment.GetEnvironmentVariable("NEW_KEY_PASSPHRASE"), cancellationToken); // and ci_ed25519.pub
Console.WriteLine(key.ToAuthorizedKeysLine()); // the line for the server's ~/.ssh/authorized_keys
SaveAsync writes the private key in the OpenSSH format (encrypted with aes256-ctr and bcrypt_pbkdf when given a passphrase),
readable only by the current user, and the public key next to it as .pub. It never overwrites an existing file.
bcrypt_pbkdf runs 16 rounds by default, as ssh-keygen does. To choose the number, as ssh-keygen -a does:
// As ssh-keygen -a 64: more bcrypt_pbkdf rounds make guessing the passphrase slower (and loading the key too).
await key.SaveAsync("ci_ed25519", Environment.GetEnvironmentVariable("NEW_KEY_PASSPHRASE"), kdfRounds: 64, cancellationToken);
Export a key to PKCS#8 or PuTTY
A key loaded from any format, or generated, can be written in another format: for PuTTY, Pageant and WinSCP, or for OpenSSL and the .NET cryptography APIs. Use it to hand a key to a tool that does not read the OpenSSH format, or to convert a key once instead of keeping copies in several formats.
var passphrase = Environment.GetEnvironmentVariable("KEY_PASSPHRASE") ?? throw new InvalidOperationException("KEY_PASSPHRASE is not set.");
using var key = await SshPrivateKey.LoadAsync("id_ecdsa", passphrase, cancellationToken);
// For PuTTY, Pageant or WinSCP: a version 3 .ppk file (and id_ecdsa.ppk.pub), readable only by the current user.
await key.SaveAsync("id_ecdsa.ppk", SshPrivateKeyFormat.Putty, passphrase, cancellationToken);
// For OpenSSL or the .NET cryptography APIs: PKCS#8 PEM, here as text for a secret store. It holds the private key: never log it.
var pem = key.ToPkcs8PrivateKey(passphrase);
using var ecdsa = ECDsa.Create();
ecdsa.ImportFromEncryptedPem(pem, passphrase);
| Format | Text | File | Encrypted with a passphrase |
|---|---|---|---|
OpenSSH (BEGIN OPENSSH PRIVATE KEY) |
ToOpenSshPrivateKey |
SaveAsync(path, SshPrivateKeyFormat.OpenSsh, ...) |
aes256-ctr, bcrypt_pbkdf (16 rounds, or your own) |
PKCS#8 (BEGIN PRIVATE KEY, BEGIN ENCRYPTED PRIVATE KEY) |
ToPkcs8PrivateKey |
SaveAsync(path, SshPrivateKeyFormat.Pkcs8, ...) |
AES-256-CBC, PBKDF2-HMAC-SHA256 with 600,000 iterations (PBES2); RSA and ECDSA only |
PuTTY .ppk version 3 |
ToPuttyPrivateKey |
SaveAsync(path, SshPrivateKeyFormat.Putty, ...) |
AES-256-CBC, Argon2id (46 MiB, one pass), HMAC-SHA256 |
Every format is read back by SshPrivateKey.LoadAsync and Parse. Each SaveAsync writes the private key readable only by the
current user and the public key next to it (path + .pub, an authorized_keys line), and never overwrites an existing file.
Limits of each format
- PKCS#8 has no comment. The key's comment is not kept; the
.pubfileSaveAsyncwrites has it. - Encrypted Ed25519 in PKCS#8 is not supported. .NET has no Ed25519, so it cannot encrypt one;
ToPkcs8PrivateKey(passphrase)throwsNotSupportedExceptionfor an Ed25519 key. Use the OpenSSH or PuTTY format, or PKCS#8 without a passphrase in a store that is encrypted itself. An unencrypted Ed25519 key is written as RFC 8410 and OpenSSL describe it. - PuTTY 0.75 or later. Version 3
.ppkfiles (Argon2) are what PuTTYgen has written since 0.75; older PuTTY versions read only version 2, which is defined with SHA-1 and is not written. The comment is kept; a comment with a line break cannot be. - Keys held elsewhere cannot be exported. A key in an agent, from
FromRsa,FromECDsaorFromSigner, or paired with a certificate throwsNotSupportedException: export the key the certificate was made for. - The text is the private key. Never log the strings these methods return, and write them only where other users cannot
read them; prefer
SaveAsync, which also clears its copy of the file's bytes.
Read a public key and its fingerprint
SshPublicKey is a public key on its own: a .pub file, an authorized_keys line, or the key of a private key
(GetPublicKey()), an agent key, a host key or a known_hosts entry.
// A .pub file, or one authorized_keys line without options: "<type> <base64> [comment]".
var key = SshPublicKey.Parse(await File.ReadAllTextAsync("id_ed25519.pub", cancellationToken));
Console.WriteLine($"{key.KeySizeBits} {key.Fingerprint} {key.Comment} ({key.KeyType})"); // as ssh-keygen -lf prints it
Console.WriteLine(key.GetFingerprint(HashAlgorithmName.MD5)); // ssh-keygen -l -E md5: MD5:aa:bb:...
// Which of the agent's keys is it? Keys are equal when their key bytes are; comments are ignored.
var agentKeys = await agent.GetKeysAsync(cancellationToken);
var match = agentKeys.FirstOrDefault(k => k.GetPublicKey() == key);
SshPublicKey.Parse reads the plain <type> <base64> [comment] form. It refuses authorized_keys options in front of the key
(restrict,command="..." ssh-ed25519 ...) rather than drop them, so a key you write back out never loses its restrictions; pass the
key part of the line. FromBlob reads the SSH wire format (what the PublicKey members hold), and Blob gives it back. A malformed key, a type name that does
not match the key, or a type SshSharp does not read fails with FormatException; TryParse returns false instead.
The types it reads are Ed25519, ECDSA (nistp256, nistp384, nistp521), RSA (up to 16384 bits, the most OpenSSH accepts; a larger
key fails with FormatException), and the FIDO security-key types
sk-ssh-ed25519@openssh.com and sk-ecdsa-sha2-nistp256@openssh.com. Certificates (-cert.pub) are SshCertificate.Parse's.
To check a signature that the key's holder made (an agent's, or one from your SshKeySigner):
// signature is in the SSH encoding (string algorithm, string signature), as an agent or an SshKeySigner makes it.
// False for a wrong or malformed signature, and for SHA-1 ssh-rsa.
var valid = key.VerifySignature(data, signature);
A security key's signatures carry authenticator data (a user-presence flag and a counter) that VerifySignature does not check:
for those keys it throws NotSupportedException. For signed files and commits, use SshSignature, which also
checks the namespace.
Use a key in the Windows key store or the TPM
// A non-exportable RSA key in a Windows key store: the TPM (Microsoft Platform Crypto Provider), a smart card, or the
// software provider. SshSharp sees the public key and asks the key for each signature.
using var rsa = new RSACng(CngKey.Open("deploy-key"));
using var key = SshPrivateKey.FromRsa(rsa, comment: "cng:deploy-key"); // rsa stays ours: disposing key does not dispose it
await using var client = await SshClient.ConnectAsync("example.com", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = [key],
HostKeyVerifier = verifier,
}, cancellationToken);
The same works with ECDsaCng and SshPrivateKey.FromECDsa, and with any software RSA or ECDsa. The
sample tool's run-cng command logs in this way.
Use a key held by a remote service
Derive from SshKeySigner: SshSharp gives it each request to sign, with the algorithm and what the signature is for, and checks
the answer against the public key before using it.
/// <summary>A key held by a remote signing service (a cloud KMS or an HSM): only the public key is local.</summary>
internal sealed class KmsSigner(IKeyService service, string keyId, ReadOnlyMemory<byte> publicKey) : SshKeySigner(publicKey)
{
// ECDSA P-256 in the service: it signs a SHA-256 digest and answers in DER.
public override DSASignatureFormat EcdsaSignatureFormat => DSASignatureFormat.Rfc3279DerSequence;
public override async ValueTask<byte[]> SignAsync(SshSignRequest request, CancellationToken cancellationToken)
{
if (request.Purpose != SshSignaturePurpose.Authentication)
{
throw new UnauthorizedAccessException("This key is for logging in only.");
}
return await service.SignDigestAsync(keyId, SHA256.HashData(request.Data.Span), cancellationToken);
}
}
/// <summary>Your key service's client.</summary>
internal interface IKeyService
{
Task<byte[]> SignDigestAsync(string keyId, byte[] digest, CancellationToken cancellationToken);
}
using var key = SshPrivateKey.FromSigner(new KmsSigner(service, "ssh-deploy", publicKeyBlob), comment: "kms:ssh-deploy");
// Use it like any other key: PrivateKeys = [key]. Each signature is checked against the public key before it is sent.
The signer's public half is signer.GetPublicKey(), an SshPublicKey: write its authorized_keys line for the servers the key
should log in to, or compare it with a key you expect.
var signer = new KmsSigner(service, "ssh-deploy", publicKeyBlob);
var line = signer.GetPublicKey().ToAuthorizedKeysLine() + " kms:ssh-deploy"; // "ecdsa-sha2-nistp256 AAAA... kms:ssh-deploy"
await File.AppendAllTextAsync("authorized_keys.d/deploy", line + "\n", cancellationToken);
Notes and pitfalls
- Order. Keys are tried in the order given. A key held in your process signs its request straight away; an agent's or a
signer's key is offered first and signs only if the server would accept it (see
Signing straight away, or asking first). A
server that allows few attempts (sshd's
MaxAuthTries, 6 by default) may disconnect before it reaches a key late in a long list: put the right key first. - Dispose keys. Disposing a loaded key clears its private key material. The client does not dispose the keys you pass it.
- RSA. RSA keys sign with
rsa-sha2-256orrsa-sha2-512, never SHA-1ssh-rsa. Keys under 2048 bits are refused. - ssh.com format keys are not read; convert them with
ssh-keygen -i. - Never log a key.
ToOpenSshPrivateKeyreturns the private key's text, for a secret store. - An in-process agent holds its keys in your process. Keys loaded from files stay in memory while the agent is used, and it
does not dispose them: keep them alive as long as the clients that forward it, and dispose them afterwards. For sensitive keys,
serve a key behind an
SshKeySigner(a KMS, an HSM), whose private half never enters the process. - A limit. Each agent channel the server opens is a connection to the agent (or work for the in-process one), and counts
against
SshClientOptions.MaxForwardedConnections(1,000) with the forwarded connections. Above it, the server's channel is refused (resource shortage), and the program on the server sees the agent fail. - The filter runs on the connection's background work, for several agent channels at once, with a token that is cancelled when the connection closes. Keep it quick, or make it asynchronous: a slow answer holds that one agent request, not the connection.
See also
- Authentication (in-depth: method order, agent constraints, keyboard-interactive, banners)
- Certificates
- Signing files and commits
- Scenario: a KMS-held key forwarded through a bastion
- Threat model: agent forwarding
- SshPrivateKey, SshPrivateKeyFormat, SshPublicKey, SshAgent and SshKeySigner in the API reference