The many uses of authorized_keys

The many uses of authorized_keys

Most of us meet ~/.ssh/authorized_keys on the day we stop typing passwords into SSH. You generate a key pair, run ssh-copy-id, and from then on your laptop is trusted by the server. For many people that is where the story ends: the file is just a list of public keys that are allowed to log in.

In fact each line of authorized_keys can carry a set of options that change what that particular key is allowed to do. A key can be limited to a single command, to connections from one address, to opening one tunnel, or to working only until a certain date. Used well, this lets you hand out keys for backups, deployments and monitoring without handing out a shell.

This article walks through those options, with practical examples. It assumes OpenSSH, which is what nearly every Linux distribution ships. Some options are fairly recent, so the OpenSSH version that introduced them is noted where it matters; run ssh -V to check yours.

The format of a line

Each non-blank line that does not start with # describes one key, in this form:

[options] keytype base64-key [comment]

A plain entry with no options looks like this (keys are shortened here and throughout):

ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGx...Qk richard@laptop

Options go at the front, separated by commas, with no spaces between them except inside double quotes:

from="192.0.2.0/24",no-pty,command="/usr/bin/uptime" ssh-ed25519 AAAAC3...Qk monitoring

The comment at the end is ignored by sshd, but it is worth filling in. When you come back to the file in two years, backup from nas01, added 2026-11 is much more useful than root@localhost.

Permissions and location

By default sshd reads .ssh/authorized_keys in the user's home directory. With StrictModes yes (the default) it will silently ignore the file if it, the .ssh directory or the home directory is writable by anyone other than the user. If a key mysteriously does not work, this is the first thing to check:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

The location is set by AuthorizedKeysFile in /etc/ssh/sshd_config. We will come back to why you might want to change it.

Locking a key to one command: command=

The most powerful option is command="...". When a key with this option is used, sshd runs the given command instead of whatever the client asked for. The client cannot get a shell, cannot run a different program, and cannot start an sftp or scp session, because all of those requests are replaced by the forced command.

command="/usr/bin/uptime" ssh-ed25519 AAAAC3...Qk uptime-check

Now this works, and is all the key can do:

$ ssh -i ~/.ssh/uptime_key server.example.org
 14:02:11 up 31 days,  2:17,  0 users,  load average: 0.04, 0.03, 0.00
$ ssh -i ~/.ssh/uptime_key server.example.org rm -rf /
 14:02:15 up 31 days,  2:17,  0 users,  load average: 0.04, 0.03, 0.00

Whatever command the client did ask for is not thrown away. It is put in the environment variable SSH_ORIGINAL_COMMAND, which lets the forced command act as a gatekeeper.

A small gatekeeper script

Suppose a monitoring server needs to run a handful of read-only commands. Rather than one key per command, point the key at a script that checks SSH_ORIGINAL_COMMAND against a list:

#!/bin/sh
# /usr/local/bin/ssh-monitor-only
# Allow a short list of exact commands, refuse everything else.

logger -t ssh-monitor "requested: ${SSH_ORIGINAL_COMMAND:-(none)}"

case "$SSH_ORIGINAL_COMMAND" in
    "uptime")        exec /usr/bin/uptime ;;
    "df")            exec /bin/df -h ;;
    "free")          exec /usr/bin/free -m ;;
    "check-updates") exec /usr/bin/apt list --upgradable ;;
    *)
        echo "Sorry, that command is not allowed." >&2
        exit 1
        ;;
esac
command="/usr/local/bin/ssh-monitor-only",restrict ssh-ed25519 AAAAC3...Qk nagios@monitor

Two points about writing scripts like this. First, match whole commands exactly, as the case above does, and never pass SSH_ORIGINAL_COMMAND to sh -c or eval: the client controls that string, and a check like "starts with df" is defeated by df; rm -rf ~. Second, run the real programs by full path so the result does not depend on PATH.

The logger line is optional but handy. It records every request in the system log, which is a good way to find out what a new tool actually runs over SSH before you write the allow list.

If you want this behaviour for every key of a user, or for a group of users, the same thing can be done in sshd_config with ForceCommand inside a Match block. The authorized_keys version has the advantage that one account can have an unrestricted key for you and restricted keys for machines.

Switching things off: restrict and the no-* options

Even when a key is locked to one command, the client can still ask for other things: a pseudo-terminal, agent forwarding, X11 forwarding and TCP port forwarding. A backup key that can also open a tunnel into your internal network is not much of a restriction. There are individual options to turn each of these off:

  • no-pty: do not allocate a terminal
  • no-port-forwarding: refuse -L, -R and -D forwarding
  • no-agent-forwarding: refuse -A
  • no-X11-forwarding: refuse -X and -Y
  • no-user-rc: do not run ~/.ssh/rc on login

Since OpenSSH 7.2 there is a much better way: restrict. It turns all of the above off in one word, and, importantly, it will also turn off any new capability added to future versions of OpenSSH. With the long list of no-* options you are only protected against the features you knew about when you wrote the line.

You can then switch individual features back on after restrict. The positive options are pty, port-forwarding, agent-forwarding, X11-forwarding and user-rc:

# A forced command that needs a terminal (for example an interactive menu)
restrict,pty,command="/usr/local/bin/console-menu" ssh-ed25519 AAAAC3...Qk helpdesk

A good habit is to start every restricted key with restrict and add back only what it needs.

Limiting where a key can be used from: from=

from="pattern-list" means the key is only accepted from matching client addresses. The list is comma-separated, takes CIDR ranges and * and ? wildcards, and an entry starting with ! excludes a match:

from="192.0.2.10" ssh-ed25519 AAAAC3...Qk backup@nas01
from="192.0.2.0/24,2001:db8::/32,!192.0.2.13" ssh-ed25519 AAAAC3...Qk office-machines

The point of from= is that a stolen key is far less useful. If the private key for the backup server leaks, the thief also has to be connecting from the backup server's address.

Hostnames are allowed too, but be careful. Matching a name needs a reverse DNS lookup of the client, and current OpenSSH does not do that unless UseDNS yes is set in sshd_config. It also means trusting whoever controls the reverse DNS for the client's address. Addresses are the safer choice.

Tunnels only: permitopen= and permitlisten=

Sometimes a key exists only to carry a tunnel, for example to reach a database that is not exposed to the internet, or to let a machine behind NAT phone home. Rather than allowing all port forwarding, you can name exactly which forwards are allowed.

Local forwarding (-L) and jump hosts

permitopen="host:port" limits the destinations a key may connect to with ssh -L, or with ssh -W, which is what ProxyJump uses. You can give the option more than once, and the port can be *:

restrict,port-forwarding,permitopen="db.internal:5432",command="/bin/false" ssh-ed25519 AAAAC3...Qk reporting-laptop

The holder of this key can run

ssh -N -L 5432:db.internal:5432 gateway.example.org

and nothing else: no shell (the forced command is /bin/false), and no tunnel to anything except port 5432 on db.internal. Note that port-forwarding has to be switched back on after restrict.

The same idea makes a tidy bastion host. A key with restrict,port-forwarding,permitopen="10.0.0.*:22" can be used as a ProxyJump to reach SSH on the internal machines, but cannot log in to the bastion itself.

Remote forwarding (-R)

permitlisten="[host:]port" (OpenSSH 7.8 and later) does the same for remote forwards, limiting which ports the client may ask the server to listen on. This is the classic "reverse tunnel" for a Raspberry Pi on a home broadband line that you want to reach from outside:

restrict,port-forwarding,permitlisten="localhost:2222",command="/bin/false" ssh-ed25519 AAAAC3...Qk pi@home

On the Pi (perhaps under autossh or a systemd service):

ssh -N -R 2222:localhost:22 [email protected]

Logged in to the server, you can now reach the Pi with ssh -p 2222 localhost, while the Pi's key cannot do anything on the server except hold that one port open.

Keys that expire: expiry-time=

Since OpenSSH 7.7 a key can be given an end date. After it passes, the key is refused:

expiry-time="20261231" ssh-ed25519 AAAAC3...Qk contractor
expiry-time="202612011800Z" ssh-ed25519 AAAAC3...Qk workshop-demo

The format is YYYYMMDD or YYYYMMDDHHMM[SS]. Times are in the server's local time zone unless they end in Z, which means UTC.

This is ideal for temporary access: a contractor for the length of a job, a friend helping fix a server for a weekend, or the demo machine at a LUG workshop. The access closes itself even if nobody remembers to remove the line, though you should still tidy the file up afterwards.

Setting variables: environment=

environment="NAME=value" sets an environment variable for sessions using that key, and can be given several times. One use is to tell a shared script who is calling it:

restrict,environment="DEPLOY_TARGET=staging",command="/usr/local/bin/deploy" ssh-ed25519 AAAAC3...Qk ci-staging
restrict,environment="DEPLOY_TARGET=production",command="/usr/local/bin/deploy" ssh-ed25519 AAAAC3...Qk ci-production

There is a catch. This option is ignored unless the server has PermitUserEnvironment enabled, and it is off by default for good reason: a user who can set variables such as LD_PRELOAD may be able to get around restrictions. Since OpenSSH 7.8 you can give PermitUserEnvironment a list of allowed variable names instead of yes, which is much safer:

# /etc/ssh/sshd_config
PermitUserEnvironment DEPLOY_TARGET

Often it is simpler to avoid the option altogether and pass an argument in the forced command instead, for example command="/usr/local/bin/deploy staging".

Practical recipes

Putting the options together, here are some patterns that come up again and again.

A backup key with rsync: rrsync

rsync over SSH runs a command of the form rsync --server ... on the remote end, with arguments that vary, so it is awkward to allow with a plain case script. The rsync project ships a helper called rrsync ("restricted rsync") for exactly this job. It checks the rsync request and confines it to one directory. On Debian and Ubuntu it is installed as /usr/bin/rrsync by recent rsync packages; on older systems you will find it among rsync's documentation as scripts/rrsync.

On a machine to be backed up, give the backup server a read-only key limited to /home:

from="192.0.2.10",restrict,command="/usr/bin/rrsync -ro /home/" ssh-ed25519 AAAAC3...Qk backup@nas01

The backup server then pulls with an ordinary rsync command. Paths are relative to the directory given to rrsync:

rsync -a -e "ssh -i ~/.ssh/backup_key" [email protected]:/ /srv/backups/desktop/home/

Use -wo instead of -ro for a key that may only upload, which suits machines that push their backups to a central server.

A backup key with Borg or restic

Modern backup tools have their own server mode designed for this. With BorgBackup, each client's key on the backup server can be confined to its own repository, and with --append-only a compromised client cannot delete its old backups:

restrict,command="borg serve --restrict-to-path /srv/borg/laptop --append-only" ssh-ed25519 AAAAC3...Qk borg@laptop

restic can work the same way: its rest-server also has an --append-only mode, or you can point restic at an SFTP-only key like the one below.

An SFTP-only key

To let a key transfer files but never get a shell, force the built-in SFTP server:

restrict,command="internal-sftp" ssh-ed25519 AAAAC3...Qk website-uploads

Plain sftp clients (and scp in OpenSSH 9.0 and later, which uses the SFTP protocol by default) will work; asking for a shell or a command will fail. If you also want to lock the user into one directory, use ChrootDirectory in a Match block in sshd_config.

A push-button key

A key that does exactly one thing is a simple and safe way to let one machine trigger an action on another: restart a service after a deployment, rebuild a website when a Git push arrives, or turn on a machine with wake-on-LAN.

restrict,command="/usr/bin/sudo /usr/bin/systemctl restart myapp" ssh-ed25519 AAAAC3...Qk ci-restart

Pair it with a sudoers rule that allows only that exact command, for example deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart myapp. The CI system can restart the application, but if its key is stolen, the worst anyone can do with it is restart the application.

One account, many people: Git hosting

Self-hosted Git services such as Gitolite and Gitea use this mechanism to let many people share a single git account. Every user's key is added with a forced command that says who the key belongs to. With Gitolite it looks like this:

command="/usr/share/gitolite3/gitolite-shell alice",restrict ssh-ed25519 AAAAC3...Qk alice
command="/usr/share/gitolite3/gitolite-shell bob",restrict ssh-ed25519 AAAAC3...Qk bob

When someone runs git push git@server:project.git, sshd knows which key was used and so which line matched, and gitolite-shell is told who is pushing. It reads SSH_ORIGINAL_COMMAND to see which repository is wanted and checks that person's permissions. This is how one Unix account can serve hundreds of users with different rights.

Beyond single keys: certificates

Copying public keys onto every server works for a handful of machines but becomes a chore as things grow. OpenSSH has its own lightweight certificate system (not X.509), and authorized_keys can take part in it too.

cert-authority

The cert-authority option says that this line is not a user's key but the key of a certificate authority (CA). Any user certificate signed by that CA is then accepted, without each user's key being listed:

cert-authority,principals="richard" ssh-ed25519 AAAAC3...Qk NELUG user CA

Making a CA is just making another key pair, which you then keep somewhere safe:

ssh-keygen -t ed25519 -f nelug_user_ca -C "NELUG user CA"

To give someone access, sign their public key. The -n option sets the principals (the names the certificate is valid for) and -V sets how long it lasts:

ssh-keygen -s nelug_user_ca -I "richard laptop" -n richard -V +52w id_ed25519.pub

This writes id_ed25519-cert.pub next to the user's key, and ssh picks it up automatically. You can inspect a certificate with ssh-keygen -L -f id_ed25519-cert.pub.

principals=

On a cert-authority line, principals="name1,name2" says which principals are acceptable. Without it, a certificate is accepted if one of its principals matches the name of the account being logged in to. With it, you can let several people into a shared account, for example principals="richard,olly" on the www account.

The other authorized_keys options still apply to a cert-authority line, so you can combine a CA with from=, restrict and so on. Certificates can also carry restrictions of their own when they are signed: ssh-keygen -O force-command=... and -O source-address=... do the job of command= and from=, but are baked into the certificate itself.

For larger setups, the CA is usually configured server-wide with TrustedUserCAKeys in sshd_config instead, but the authorized_keys form is a gentle way to try certificates on one account first.

Odds and ends

Hardware security keys

OpenSSH 8.2 added keys held on FIDO security keys such as YubiKeys (the [email protected] and [email protected] types). By default the user must touch the key for each login. Two options adjust this: no-touch-required drops the touch requirement (useful for automation, but it throws away much of the benefit), and verify-required (OpenSSH 8.9) insists that the key also checked the user's PIN or fingerprint.

VPN tunnels: tunnel=

OpenSSH can carry a layer 2 or layer 3 VPN with ssh -w, if PermitTunnel is enabled. tunnel="n" forces a key to use tun device number n on the server. This is rarely used now that WireGuard exists, but it is there.

Keeping the user out of their own file

All of these restrictions have one weakness: if the account can write to its own authorized_keys, a restricted key could be used to edit the file and remove its own restrictions. A good forced command makes that impossible in practice, but for accounts that only exist to be restricted (backup, deployment, tunnels) it is better to move the file somewhere the user cannot change. In sshd_config:

AuthorizedKeysFile /etc/ssh/authorized_keys/%u .ssh/authorized_keys

Files under /etc/ssh/authorized_keys/ are owned by root and readable by the user. %u is replaced with the user name, and %h with the home directory. Keeping .ssh/authorized_keys as a second entry means normal users carry on as before. For full central management, AuthorizedKeysCommand can fetch keys from a program instead (from LDAP, for example).

Debugging

When a key does not behave as you expect:

  • Run the client with ssh -v. It shows whether the key was offered and accepted, and the server sends back which options were applied, as debug1: Remote: ... lines.
  • Read the server log (journalctl -u ssh on Debian and Ubuntu, journalctl -u sshd on Fedora and others). Permission problems and bad option syntax are reported there, not to the client.
  • ssh-keygen -lf ~/.ssh/authorized_keys lists the fingerprint of every key in the file. Compare these with the fingerprint in the log to see which line was used.
  • A typo in the options usually makes sshd ignore the whole line, so the key simply stops working. Check for stray spaces, and for curly quotes if you pasted the line from a web page or a word processor.

Summary

A quick reference for the options covered here:

  • command="...": always run this command; the client's request is in SSH_ORIGINAL_COMMAND
  • restrict: turn off forwarding, terminals and ~/.ssh/rc, now and in future versions
  • pty, port-forwarding, agent-forwarding, X11-forwarding, user-rc: turn one feature back on after restrict
  • no-pty, no-port-forwarding, no-agent-forwarding, no-X11-forwarding, no-user-rc: turn one feature off
  • from="...": only accept the key from these addresses
  • permitopen="host:port": limit -L and -W forwarding to these destinations
  • permitlisten="[host:]port": limit -R forwarding to these listening ports
  • expiry-time="...": refuse the key after this date
  • environment="NAME=value": set a variable (needs PermitUserEnvironment)
  • cert-authority and principals="...": trust certificates signed by this CA
  • no-touch-required, verify-required: adjust FIDO security key checks
  • tunnel="n": force a tun device number

The full list, with all the details, is in the AUTHORIZED_KEYS FILE FORMAT section of the sshd(8) manual page, so man sshd is worth a read with this article in mind. The next time you are about to give a script or another machine a key to one of your servers, ask what it actually needs to do, and write a line that allows that and nothing more.

Comments on this site are closed. To ask a question or get in touch, please use the mailing list.