Tuesday July 20 2021

Simple and explicit SSH key management

SSH keys can have a problem of being user supplied and updated, as well as being somewhat difficult to keep track of exactly who and what has access to the system at a since they’re in each user’s home directory.

This article is in a similar vein to my previous one on SSH key handling and is worth a read.

Before we get too far, this is the resulting file format saved in /etc/ssh/keys:

# username::key::other::info
mitch::ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDhK3hkZto5wqcBHwBcS4IpK1jpQwqItbtp7Rb3Ir1+B
bob::ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIF8WQqO1Lv9fksA+mVJbaqlrlUINWTqRYr9YyUGlKTQ6

It should be pretty self explanatory as to how we can use this single file as a database of sorts for all of the SSH keys allowed in on this system. It works much like /etc/group or /etc/passwd except we’re using double colons as the field separator instead of one.

To facilitate the reading of this file, we’re going to use this short shell script:

#!/bin/sh
_u="$1"; shift
grep "^$_u" "$@" | awk -F:: '{print $2}'

I save this as /etc/ssh/auth.sh typically.

From there we can adjust /etc/ssh/sshd_config to use it:

AuthorizedKeysCommand /etc/ssh/auth.sh "%u" /etc/ssh/keys
AuthorizedKeysCommandUser sshd

Depending on the system in question you may need to adjust AuthorizedKeysCommandUser to be something other than sshd

Be sure that the user has permissions to execute the script and read the central keys file.

Now, disable AuthorizedKeysFile explicitly by setting it to none:

AuthorizedKeysFile none

sshd requires restarts for configuration changes to take effect.

Now you’re done, at a glance you can pull up /etc/ssh/keys on your system and know exactly who and what has access without trudging through home directories.

This does have the side effect of preventing users from managing their own keys but sometimes this is exactly what you want.

A central file like this is also much easier to lay down from a configuration management tool like Ansible and keep in sync across a large number of systems, this is especially true when you need to ensure that some users have had their keys removed from all of the machines.