Certificates
An OpenSSH user certificate is a public key signed by a certificate authority (CA), with the principals (user names) it may log in
as and a validity period. Servers that trust the CA (sshd's TrustedUserCAKeys) accept it without an authorized_keys entry, which
is how many organizations hand out short-lived SSH access. Host certificates work the other way, letting clients trust servers by
their CA.
SshSharp logs in with certificates, checks them, and issues them: an application can be the CA.
When to use
- Your organization issues SSH certificates (
ssh-keygen -s, HashiCorp Vault's SSH secrets engine, step-ca, Teleport, cloud identity-aware proxies). - You want access that expires on its own instead of keys in
authorized_keys. - You want to issue them yourself, from an application: short-lived certificates for CI jobs or a bastion, or host certificates
for servers you provision, without running
ssh-keygen -s.
Log in with a certificate
using var key = await SshPrivateKey.LoadAsync("id_ed25519", cancellationToken: cancellationToken);
var certificate = SshCertificate.Parse(await File.ReadAllTextAsync("id_ed25519-cert.pub", cancellationToken));
if (certificate.ValidBefore < DateTimeOffset.UtcNow.AddMinutes(5))
{
throw new InvalidOperationException($"Certificate {certificate.KeyId} expires at {certificate.ValidBefore:u}; renew it.");
}
Console.WriteLine($"{certificate.KeyId}: principals {string.Join(", ", certificate.Principals)}, signed by {certificate.AuthorityFingerprint}");
await using var client = await SshClient.ConnectAsync("example.com", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = [key.WithCertificate(certificate), key], // the certificate first, the plain key as a fallback
HostKeyVerifier = verifier,
}, cancellationToken);
WithCertificate pairs the key with its certificate; the pair is offered first, and the plain key after it in case the server
does not take the certificate.
A certificate for an agent key
// A short-lived certificate from your CA, for a key the agent holds.
var agent = SshAgent.FromEnvironment() ?? throw new InvalidOperationException("No SSH agent is running.");
var certificate = SshCertificate.Parse(await File.ReadAllTextAsync("id_ed25519-cert.pub", cancellationToken));
var agentKey = (await agent.GetKeysAsync(cancellationToken)).First(k => k.PublicKey.Span.SequenceEqual(certificate.PublicKey.Span));
var options = new SshClientOptions { UserName = "deploy", PrivateKeys = [agentKey.WithCertificate(certificate)], HostKeyVerifier = verifier };
From ssh_config
Connecting by alias finds certificates as ssh does: CertificateFile entries, and <identity>-cert.pub next to each identity
file.
Trust hosts by their certificates
A host certificate lets clients trust every server the CA signed, without a known_hosts line per server. Add the CA to
known_hosts:
@cert-authority *.example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA...
KnownHostsVerifier then accepts a host certificate from that CA for matching host names, within its validity period. A
certificate that cannot be used (expired, not issued for the name connected to, or signed with an algorithm
CASignatureAlgorithms leaves out) is logged as a warning, and its key is checked as a plain key, as ssh does: see Host certificates that cannot be used.
To trust only authorities that sign with some algorithms (Ed25519 only, say), set SshClientOptions.CASignatureAlgorithms, or
CASignatureAlgorithms in ssh_config 1.2: see
Trust host certificates only from some kinds of authority.
To apply your own rules, see the custom verifier.
Check a certificate
An application that receives certificates (a bastion, a portal, a job runner) checks one as sshd does with IsValidFor: issued by
the CA you trust, of the right type, with a valid signature, within its validity window, for the principal, and without critical
options it would have to enforce. It returns why not:
// The authority you trust, and a certificate someone presents (a user's -cert.pub, say, uploaded to your bastion's portal).
var trustedCa = SshPublicKey.Parse(await File.ReadAllTextAsync("user_ca.pub", cancellationToken));
var certificate = SshCertificate.Parse(await File.ReadAllTextAsync("id_ed25519-cert.pub", cancellationToken));
if (!certificate.IsValidFor(trustedCa, SshCertificateType.User, "deploy", DateTimeOffset.UtcNow, out var reason))
{
throw new InvalidOperationException($"Certificate {certificate.KeyId} is not acceptable: {reason}.");
}
The parts are public too, for your own rules:
// Only the signature: proves the holder of AuthorityKey issued it, not that you trust that authority.
var signed = certificate.VerifySignature();
// Your own rules, for an application that enforces the critical options itself.
var acceptable = signed
&& certificate.GetAuthorityKey() == trustedCa
&& certificate.Type == SshCertificateType.User
&& certificate.IsValidAt(DateTimeOffset.UtcNow)
&& certificate.Principals.Contains("deploy")
&& certificate.CriticalOptions.Keys.All(option => option == SshCertificateBuilder.ForceCommand);
What they mean, as OpenSSH has it:
| Check | Rule |
|---|---|
VerifySignature() |
The CA's signature over the certificate. SHA-1 (ssh-rsa) signatures are refused, an RSA CA needs 2048 bits or more, and Ed25519 is checked strictly. It does not say you trust the CA: anyone can make one. |
IsValidAt(time) |
valid_after <= time < valid_before, in whole seconds. ValidAfter is DateTimeOffset.UnixEpoch for "always", ValidBefore is DateTimeOffset.MaxValue for "forever" (0xffffffffffffffff). |
| Principals | A user certificate must list the user name exactly. A host certificate's principals are patterns (*.example.com), matched without regard to case. A certificate with no principals is refused, as sshd refuses one from TrustedUserCAKeys and ssh a host's; only an authorized_keys cert-authority line without principals= takes it as any user. |
| Critical options | IsValidFor refuses a certificate with any (force-command, source-address, verify-required): they restrict what it allows, and only your code can enforce them. |
IsValidFor does not check revocation; see Check revocation.
Certificates that are not read
Before any of these checks, a certificate must be well formed, and SshCertificate.Parse throws FormatException for one that is
not. Besides a truncated or padded certificate, that includes these rules from draft-ietf-sshm-cert:
- At most 256 principals. This is OpenSSH's limit (
SSHKEY_CERT_MAX_PRINCIPALS): 256 are read, 257 are not. - Critical options and extensions sorted by name, each once. The names must be in strictly increasing byte order, the order
ssh-keygenandSshCertificateBuilderwrite them in (sopermit-X11-forwardingcomes beforepermit-agent-forwarding). A name out of order or listed twice makes the certificate malformed: two entries for one name would leave open which one applies.
The same rules apply wherever SshSharp reads a certificate: a server's host certificate during the key exchange (the connection
fails with SshHostKeyException, even when its authority is trusted), a CertificateFile or -cert.pub found from ssh_config
(skipped, and logged as an unreadable identity is), and a certificate an agent lists (not offered). A revocation list is the
exception: a certificate line there revokes the key it certifies whatever its principals and options, since refusing to read it
would leave that key accepted.
Read extension values
Extensions lists the extensions' names; ExtensionValues has their values too. The standard ones (permit-pty and the rest) have
an empty value; a vendor's own extension (login@example.com, written with ssh-keygen -O extension:login@example.com=deploy or the
builder's Extensions) carries what its CA put there:
// A vendor extension's value: null when the CA did not write the extension.
var login = certificate.ExtensionValues.TryGetValue("login@example.com", out var value) ? value : null;
var canPty = certificate.ExtensionValues.ContainsKey("permit-pty"); // the standard ones have no value
Servers ignore extensions they do not know, so a vendor extension means only what your application makes of it, on the CA's word.
Check revocation
SshKeyRevocationList reads the revocation list sshd's RevokedKeys names: an OpenSSH KRL (the binary file ssh-keygen -k writes)
or a text file of public keys (IsKrl says which it read). It answers for a certificate (revoked by serial or key id for its authority, or because its key or its
authority's key is) and for a plain key (listed, or listed by fingerprint), as ssh-keygen -Q does:
// The file sshd's RevokedKeys names: a KRL from ssh-keygen -k, or one public key per line.
var revoked = await SshKeyRevocationList.LoadAsync("/etc/ssh/revoked_keys", cancellationToken);
if (revoked.IsRevoked(certificate)) // its serial, its key id, its key, or its authority's key
{
throw new InvalidOperationException($"Certificate {certificate.KeyId} (serial {certificate.Serial}) is revoked.");
}
var keyRevoked = revoked.IsRevoked(userKey); // a plain key, from an authorized_keys line, say
A malformed KRL, or one with a section or critical extension this library does not know, throws FormatException rather than being
read in part: treat that as "everything is revoked", as ssh does for RevokedHostKeys. The KRL's signature is not verified; the file
is trusted as local configuration. Serial 0 (a certificate issued without one) is never revoked by serial: give each certificate its
own Serial.
In a text file, a certificate line revokes the key it certifies, as in sshd. That includes FIDO security-key certificates
(sk-ssh-ed25519-cert-v01@openssh.com, sk-ecdsa-sha2-nistp256-cert-v01@openssh.com): the security key itself is revoked. A
certificate line of a type SshSharp accepts (Ed25519, ECDSA, RSA, FIDO) whose key cannot be read (bad base64, a truncated
certificate) throws FormatException for the whole file instead of being skipped, so a key the list means to revoke is never
accepted. A certificate line of a type SshSharp never accepts (ssh-dss-cert-v01@openssh.com, or one it does not know) is skipped,
and so are other lines that do not parse, as in OpenSSH. The certificate's authority is not checked: the line revokes its key
whoever signed it.
Act as a certificate authority
SshCertificateBuilder issues certificates as ssh-keygen -s does. Give it the key to certify, the type and a key id, set the
principals and the end of the validity window, and sign with the CA's key:
// The CA key, read from a secret store (see below for one that stays in an agent or a KMS).
using var ca = SshPrivateKey.Parse(Environment.GetEnvironmentVariable("SSH_USER_CA_KEY") ?? throw new InvalidOperationException("SSH_USER_CA_KEY is not set."));
// A key for this build only, and a certificate for it that expires with the build.
using var key = SshPrivateKey.Generate(SshKeyType.Ed25519, $"ci-build-{buildId}");
var builder = new SshCertificateBuilder(key.GetPublicKey(), SshCertificateType.User, keyId: $"ci-build-{buildId}")
{
Serial = buildNumber, // unique, so a revocation list can name it
Principals = { "deploy" }, // the user it may log in as
ValidBefore = DateTimeOffset.UtcNow.AddMinutes(30),
};
builder.Extensions.Clear(); // commands only: no terminal, no forwarding
var certificate = await builder.SignAsync(ca, cancellationToken);
await using var client = await SshClient.ConnectAsync("build.example.com", 22, new SshClientOptions
{
UserName = "deploy",
PrivateKeys = [key.WithCertificate(certificate)],
HostKeyVerifier = verifier,
}, cancellationToken);
sequenceDiagram
participant Job as CI job
participant App as Your app (CA)
participant Signer as Agent or KMS (CA key)
participant Server as sshd (TrustedUserCAKeys)
Job->>Job: Generate a key for this job
Job->>App: Public key, job id
App->>App: SshCertificateBuilder: principals, 30 minutes, no extensions
App->>Signer: Sign (purpose: Certificate)
Signer-->>App: Signature
App-->>Job: Certificate
Job->>Server: Log in with key + certificate
Server->>Server: CA trusted, signature, validity, principal, options
A host certificate, for sshd_config's HostCertificate:
var hostKey = SshPublicKey.Parse(await File.ReadAllTextAsync("ssh_host_ed25519_key.pub", cancellationToken));
var builder = new SshCertificateBuilder(hostKey, SshCertificateType.Host, keyId: "web1")
{
Principals = { "web1.example.com", "web1" },
ValidBefore = DateTimeOffset.UtcNow.AddDays(90),
};
var certificate = await builder.SignAsync(ca, cancellationToken);
// sshd_config: HostCertificate /etc/ssh/ssh_host_ed25519_key-cert.pub
await File.WriteAllTextAsync("ssh_host_ed25519_key-cert.pub", certificate.ToAuthorizedKeysLine() + "\n", cancellationToken);
What the builder does for you:
- Validity. There is no default end: set
ValidBefore(DateTimeOffset.MaxValuefor a certificate that never expires, which is rarely what you want).ValidAfterdefaults to one minute before signing, so a server whose clock is a little behind accepts a new certificate at once. - Extensions. A user certificate starts with what
ssh-keygengives one:permit-X11-forwarding,permit-agent-forwarding,permit-port-forwarding,permit-ptyandpermit-user-rc.Extensions.Remove(...)takes one away,Extensions.Clear()all of them (asssh-keygen -O clear). A host certificate starts with none. - Critical options.
ForceCommandandSourceAddresstake a value;VerifyRequiredtakes none. Host certificates have none. - Checks. At least one principal and at most 256 (OpenSSH refuses a certificate with more: issue several); option and extension names that are standard or a vendor's own (
name@example.com); asource-addresslist of addresses or CIDR blocks; a validity window that is not empty. A mistake throwsInvalidOperationExceptionbefore anything is signed. - Encoding. As
PROTOCOL.certkeyshas it, for Ed25519, ECDSA and RSA keys: a 32-byte random nonce, options and extensions sorted by name and each once, and an RSA CA signing withrsa-sha2-512(asssh-keygenby default), never SHA-1ssh-rsa. The signature is checked against the CA's key before the certificate is returned.
Write a certificate with certificate.ToAuthorizedKeysLine(), the line a -cert.pub file holds; ssh-keygen -L -f lists it.
Keep the CA key out of the process
SignAsync takes any SshPrivateKey, including one an SSH agent holds:
// The CA key stays in the agent (ssh-add on the signing host); only its fingerprint is configuration.
var caFingerprint = Environment.GetEnvironmentVariable("SSH_USER_CA_FINGERPRINT") ?? throw new InvalidOperationException("Set SSH_USER_CA_FINGERPRINT.");
var agent = SshAgent.FromEnvironment() ?? throw new InvalidOperationException("No SSH agent is running.");
var ca = (await agent.GetKeysAsync(cancellationToken)).Single(k => k.Fingerprint == caFingerprint);
or one in a key vault, KMS or HSM through an SshKeySigner. The signer sees SshSignaturePurpose.Certificate, so the CA key can be
allowed to issue certificates and nothing else:
/// <summary>
/// A certificate authority whose key is in a key service: it signs certificates only, so a stolen API credential cannot use the CA
/// key to log in anywhere. <c>signDigest</c> stands for your KMS client (an Ed25519 key signs the data itself; see SshKeySigner).
/// </summary>
internal sealed class CertificateAuthoritySigner(byte[] publicKey, Func<byte[], CancellationToken, Task<byte[]>> signDigest)
: SshKeySigner(publicKey)
{
// An ECDSA P-256 key in the service: it signs a SHA-256 digest and answers DER.
public override DSASignatureFormat EcdsaSignatureFormat => DSASignatureFormat.Rfc3279DerSequence;
public override async ValueTask<byte[]> SignAsync(SshSignRequest request, CancellationToken cancellationToken) =>
request.Purpose == SshSignaturePurpose.Certificate
? await signDigest(SHA256.HashData(request.Data.Span), cancellationToken)
: throw new UnauthorizedAccessException("The CA key issues certificates only.");
}
using var ca = SshPrivateKey.FromSigner(new CertificateAuthoritySigner(caPublicKeyBlob, kms.SignDigestAsync), comment: "kms:user-ca");
Notes and pitfalls
- Principals. The server checks that the user name you log in as is one of the certificate's principals
(
certificate.Principals); a mismatch is an ordinary authentication failure. - Expiry. An expired certificate is refused by the server; check
ValidBeforeand renew in time, as above. - Critical options such as
force-commandorsource-addressare enforced by the server (certificate.CriticalOptionslists them). - Revocation. Servers revoke user certificates with
RevokedKeys; on the client side,RevokedHostKeyscan revoke host certificates by serial or key id, and an application checks either kind withSshKeyRevocationList. Give each certificate you issue its ownSerialso that a revocation list can name it; better still, issue certificates short enough that revoking them is rarely needed. - The CA key is the keys to the kingdom. Whoever can sign with it can log in as any principal on every server that trusts it. Keep it in an agent or a key service, allow it to sign certificates only, issue for the shortest time that works, and name principals exactly. See the threat model.
- Key ids are logged by sshd when a certificate is used: make them say who or what it was for (a job id, a ticket).
See also
- Jump host sample: a five-minute certificate issued in the program, used for a jump host and the destination
- Scenario: short-lived certificates for CI jobs
- Authentication: certificates
- Keys held elsewhere
- Host keys
- SshCertificate, SshCertificateBuilder and SshKeyRevocationList in the API reference