Generating and Using OpenSSH Host Certificates

Lee Painter

Creating OpenSSH Certificates is now possible from the Maverick Legacy API via the SshCertificateAuthority helper class. This article is a quick reference for users that understand what OpenSSH certificates are and already understand how to use these with the standard OpenSSH client and server.

A cheat sheet is available in our blog which outlines the basic configuration steps required to use and generate SSH certificates using the OpenSSH command-line clients.

Creating a Certificate Authority

There is nothing special about an SSH certificate authority, it's just a plain old SSH private/public key pair. We create one like any other SSH key.

SshKeyPair caKey = SshKeyPairGenerator.generateKeyPair(SshKeyPairGenerator.ED25519);

This should be stored like any other private key

SshKeyUtils.savePrivateKey(caKey, "secret", "My Certificate Authority", new File("caKey"));

This will result in two files stored in the current working directory caKey and caKey.pub. This is your certificate authority private key and should be kept secure. 

It's general practice to use separate CA for users and host keys. However, in this article, I will simply refer to this CA key in future examples. 

Generating Host Certificates

SSH Certificates still require that we generate a public/private key for the host. So we generate one as usual with the SshKeyPairGenerator.

SshKeyPair hostKey = SshKeyPairGenerator.generateKeyPair(SshKeyPairGenerator.ED25519);

Before saving the key, we can generate an SSH Certificate for this key using the API. We can specify the serial number, the hostname, and the validity of the certificate (in days).

SshCertificate cert = SshCertificateAuthority.generateHostCertificate(userKey, 0L, "localhost", 365, caKey);

We can now save the certificate to distribute to the host configuration.

SshKeyUtils.saveCertificate(cert, "", "Localhost's Certificate", new File("hostKey"));

This will result in three files stored in the current working directory hostKey the private key, hostKey.pub the public key, and hostKey-cert.pub the certificate file. All these files should be distributed to the server.

Using Host Certificates

We can load the SshCertificate back with the following call:

SshCertificate cert = SshKeyUtils.getCertificate(new File("hostKey"), "");

Note that we now have a SshCertificate object instead of a SshKeyPair. We can pass this to the API to use as a host key calling the SshContext method addHostKey.

sshContext.loadSshCertificate(cert);