Audits OpenSSH authorized_keys files offline: SHA256 fingerprints like ssh-keygen -lf, weak DSA and short RSA keys, duplicates, missing comments, unrestricted automation keys, expired or loose options, plus keys of people who left or were never known, using an optional owners CSV. Stdlib Python.
---
name: ssh-authorized-keys-auditor
description: Audits OpenSSH authorized_keys files offline: SHA256 fingerprints like ssh-keygen -lf, weak DSA and short RSA keys, duplicates, missing comments, unrestricted automation keys, expired or loose options, plus keys of people who left or were never known, using an optional owners CSV. Stdlib Python.
---
# SSH Authorized Keys Auditor
You help developers, sysadmins and team leads answer a simple question that is surprisingly hard on real servers: who can log in here with a key, and should they still be able to? `authorized_keys` files grow for years. People change laptops and add a new key without removing the old one, contractors finish their projects, a backup host from 2019 still has a 1024-bit RSA key with full shell access, and nobody remembers what `AAAAC3...` without a comment belongs to. You read the files, list every key with its fingerprint, size and owner, and point at the few lines that need action.
You work offline on copies of the files. You never connect to servers, never ask for private keys and never test a key by logging in with it. A finding means "decide about this line", not "this server is compromised".
## Files in this skill
- `scripts/ssh_keys_audit.py` - parses one or more `authorized_keys` files (options with quoted values, key type, base64 blob, comment), computes the SHA256 fingerprint exactly like `ssh-keygen -lf`, reads the real RSA/DSA key size from the blob, and prints findings K01-K12 + E01 with a severity; `--owners` maps keys to people, `--format text|md|json|csv`, `--fail-on` for CI, `--today` for reproducible checks, `--self-test` runs 21 checks (Python 3.8+ standard library only)
- `references/key-types-and-strength.md` - which key types and sizes to accept in 2026, hardware-backed `sk-` keys, and how to replace weak keys without locking anyone out
- `references/authorized-keys-options.md` - `from=`, `command=`, `restrict`, `expiry-time=`, `permitopen=` and friends, with safe patterns for automation keys
- `templates/access-review-report.md` - a short access review report for one server or a fleet
- `examples/authorized_keys` - a fictional `deploy` user on `web-01` with 16 key lines (public keys only; the matching private keys were deleted after generating them)
- `examples/owners.csv` - the owners list for the example, with one person who left and one ended contract
## Workflow
### 1. Collect the files
Copy the files instead of auditing on the live server:
```
scp web-01:/home/deploy/.ssh/authorized_keys ./web-01.deploy.authorized_keys
sudo find /home /root -name 'authorized_keys*' -path '*/.ssh/*' 2>/dev/null # on the server, to find all of them
grep -i AuthorizedKeysFile /etc/ssh/sshd_config /etc/ssh/sshd_config.d/* 2>/dev/null # non-default locations
```
Also check whether `AuthorizedKeysCommand` or SSH certificates (`TrustedUserCAKeys`) are used; keys served that way are not in these files and need a separate review.
### 2. Build or update the owners list (optional, recommended)
`owners.csv` has the columns `match,owner,status,last_review,note`. `match` is either the exact key comment or the `SHA256:` fingerprint (safer, because comments can be edited). `status` is `active`, `left`, `revoked`, `inactive` or `offboarded`. Start with `--format csv` output to get every fingerprint, then fill in owners with the team.
### 3. Run the audit
```
python3 scripts/ssh_keys_audit.py web-01.deploy.authorized_keys
python3 scripts/ssh_keys_audit.py hosts/*.authorized_keys --owners owners.csv --format md > access-review.md
python3 scripts/ssh_keys_audit.py authorized_keys --owners owners.csv --fail-on medium # CI or cron gate
python3 scripts/ssh_keys_audit.py authorized_keys --format csv > key-inventory.csv
python3 scripts/ssh_keys_audit.py --self-test
```
Exit code 0 = nothing at or above `--fail-on` (default high; info never fails), 1 = findings at or above it, 2 = unreadable input or owners file.
| Code | Severity | Meaning |
|---|---|---|
| K01 | high | DSA (`ssh-dss`) key |
| K02 | high | RSA key shorter than 2048 bits |
| K03 | medium | RSA key shorter than `--min-rsa-bits` (default 3072) |
| K04 | medium | the same public key appears more than once (also across files) |
| K05 | low | key without a comment |
| K06 | medium | automation-looking key (ci, deploy, backup, bot, cron, ansible...) with neither `from=` nor `command=` |
| K07 | high | `expiry-time=` already in the past |
| K08 | medium | `command=` key that still allows forwarding or a PTY |
| K09 | high | owner marked left / revoked in the owners file |
| K10 | medium | key not in the owners file |
| K11 | low | owners file review older than `--review-days` (default 365) |
| K12 | info | port forwarding explicitly allowed (`permitopen`, `permitlisten`, `restrict,port-forwarding`) |
| E01 | medium | line that cannot be parsed (truncated paste, bad base64, type mismatch) |
### 4. Decide per finding
Work from high to low with the two reference files:
- K09 and K07: remove the line now, after checking that no running job depends on it; tell the owner's manager.
- K01 and K02: ask the owner for a new Ed25519 key (or `sk-ssh-ed25519` on a hardware key), add it, confirm the login works, then remove the old line.
- K10 and K05: find the owner with the fingerprint (`ssh-keygen -lf`, git history of config management, the team chat). If nobody claims it within the agreed time, disable it by commenting it out first, then remove it.
- K04: keep one line; duplicates often hide a key that was "removed" but still has a second copy.
- K06 and K08: restrict automation keys with `from=` the runner's network and `restrict` plus a forced `command=` when the job only needs one action.
- E01: a broken line is ignored by sshd but often means someone pasted a key wrongly and is now locked out or has a second copy elsewhere.
### 5. Report
Fill `templates/access-review-report.md`: summary counts, the actions table with owner and due date, what was removed, and what is still unknown. Re-run the script after the changes and attach the clean output.
## Rules
- Never ask for, read or store private keys. Public keys and fingerprints are enough for every check here.
- Never remove keys on a live server without a second session open and a tested way back in; removing the wrong key can lock out the only admin.
- Treat the owners file as the source of truth only if someone reviewed it; say when it is old (K11).
- Report what the file says, not guesses about who uses a key. If the owner is unknown, say so.
- Keys in config management (Ansible, Puppet, cloud-init, NixOS) will come back after manual removal; fix them at the source.
FILE:references/key-types-and-strength.md
# Key types and strength (OpenSSH, 2026)
| Type in `authorized_keys` | Verdict | Notes |
|---|---|---|
| `ssh-ed25519` | recommended | Fast, small, fixed 256-bit strength. Default for new keys. |
| `sk-ssh-ed25519@openssh.com` | recommended for admins | Private key lives on a FIDO2 hardware key (YubiKey, SoloKey); a touch is needed for each login. Needs OpenSSH 8.2+ on both sides. |
| `ecdsa-sha2-nistp256/384/521` | acceptable | Fine in practice; some teams prefer Ed25519 for simpler, safer implementations. |
| `sk-ecdsa-sha2-nistp256@openssh.com` | acceptable | Hardware-backed ECDSA for older FIDO keys without Ed25519 support. |
| `ssh-rsa` 3072+ bits | acceptable | Still widely used. 4096 is common. Keep the key, but new keys should be Ed25519. |
| `ssh-rsa` 2048 bits | replace when convenient (K03) | Not broken today, but below the 3072-bit level many policies (NIST, BSI) ask for beyond 2030. |
| `ssh-rsa` below 2048 bits | replace now (K02) | 1024-bit RSA is considered breakable by well-funded attackers. OpenSSH 9.1+ refuses RSA keys below 1024 bits by default (`RequiredRSASize`), and some distributions raise the minimum further. |
| `ssh-dss` (DSA) | replace now (K01) | Fixed 1024-bit size. Disabled by default since OpenSSH 7.0 and removed completely in OpenSSH 10.0; if it still works, the server runs an old or specially configured sshd. |
## The signature algorithm is not the key type
The `ssh-rsa` key type is fine with modern signatures (`rsa-sha2-256`, `rsa-sha2-512`). What OpenSSH 8.8 disabled by default is the old SHA-1 signature algorithm, also called `ssh-rsa`. If very old clients or devices fail to log in after an upgrade, that is usually the reason, not the key itself.
## Fingerprints
`ssh-keygen -lf <file>` prints the size, the SHA256 fingerprint and the comment of every key in a public key or `authorized_keys` file. The fingerprint is the SHA256 hash of the decoded base64 key blob, base64-encoded without `=` padding. The audit script computes the same value, so you can match keys with server logs (`sshd` logs `Accepted publickey for deploy ... SHA256:...`) and with what people see on their laptops (`ssh-keygen -lf ~/.ssh/id_ed25519.pub`).
Older tools show MD5 fingerprints (`ssh-keygen -E md5 -lf ...`, format `aa:bb:...`). Ask for SHA256 to avoid confusion.
## Replacing a weak or old key without lockouts
1. The owner creates a new key on their machine: `ssh-keygen -t ed25519 -C "name@device-2026"` (or `-t ed25519-sk` with a hardware key).
2. They send only the `.pub` file, or the public line, through a channel you trust.
3. Add the new line, keep the old one, and ask them to log in with the new key (`ssh -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes host`).
4. Check the `sshd` log for the new fingerprint, then remove the old line.
5. Update the owners file with the new fingerprint and today's review date.
For automation keys, generate the new key on the machine that uses it (the CI runner, the backup host), never on a laptop, and store the private key only there or in the CI secret store.
## Good comment conventions
Comments are free text and can be changed by anyone who edits the file, so they are hints, not proof. A useful convention is `person-or-service@device-year`, for example `alice@laptop-2026` or `ci-deploy@build-runner`. Match owners by fingerprint when it matters.
FILE:references/authorized-keys-options.md
# authorized_keys options that matter
An `authorized_keys` line is: `[options] keytype base64-key [comment]`. Options are comma-separated; values with spaces or commas are in double quotes, for example `from="10.0.0.0/8,192.168.1.5"`. A line without options gives a full interactive shell with all forwarding allowed, as far as `sshd_config` permits.
## Options checked by the script
| Option | What it does | Typical use |
|---|---|---|
| `from="pattern-list"` | Only accepts the key from matching client addresses or hostnames (CIDR ranges allowed). | Pin automation keys to the CI runner or backup host network. |
| `command="cmd"` | Runs only this command, whatever the client asks for; the original request is in `SSH_ORIGINAL_COMMAND`. | Backup receivers, git-only access, one-purpose jobs. |
| `restrict` | Turns off port, agent and X11 forwarding, PTY allocation and `~/.ssh/rc` in one word (OpenSSH 7.2+). Future restrictions are included automatically. | Start every non-human key with it. |
| `no-port-forwarding`, `no-agent-forwarding`, `no-X11-forwarding`, `no-pty` | The older one-by-one form of `restrict`. | Servers with OpenSSH older than 7.2. |
| `port-forwarding`, `agent-forwarding`, `pty`, `X11-forwarding` | Turn single features back on after `restrict`. | A tunnel key that needs only port forwarding. |
| `permitopen="host:port"` / `permitlisten="port"` | Limit local / remote forwarding to these destinations. | Database tunnels. |
| `expiry-time="YYYYMMDD[HHMM[SS]]"` | sshd refuses the key after this time (OpenSSH 8.2+). | Contractors, temporary support access, break-glass keys. |
| `principals="..."`, `cert-authority` | Used with SSH certificates instead of plain keys. | Fleets that use a CA; review the CA separately. |
## Safe patterns
Human admin with a hardware key:
```
sk-ssh-ed25519@openssh.com AAAA... erin@yubikey
```
CI deploy key that may only run the deploy script from the runner network:
```
from="10.20.0.0/16",restrict,command="/usr/local/bin/deploy.sh" ssh-ed25519 AAAA... ci-deploy@build-runner
```
Backup receiver (only rsync into one directory):
```
restrict,command="/usr/bin/rrsync /srv/backups/web-01" ssh-ed25519 AAAA... backup@backup-02
```
Temporary vendor access for two weeks:
```
expiry-time="20261215",restrict,pty ssh-ed25519 AAAA... vendor-support@contractor
```
Database tunnel only:
```
restrict,port-forwarding,permitopen="localhost:5432" ssh-ed25519 AAAA... db-tunnel@ops
```
## Things that look safe but are not
- `command=` without `restrict` (or the four `no-*` options) still lets the client open port forwards and use agent forwarding: K08.
- Deleting a key from one `authorized_keys` file does not remove it from other users, other servers, golden images or config management.
- `from=` with a hostname depends on reverse DNS; prefer IP ranges.
- An expired `expiry-time` key no longer works, but it shows that the cleanup process is not running: K07.
## sshd_config settings worth checking at the same time
`PubkeyAuthentication yes`, `PasswordAuthentication no`, `PermitRootLogin prohibit-password` or `no`, `AuthorizedKeysFile` (which files are read), `PubkeyAcceptedAlgorithms` (which key types are allowed), and `LogLevel VERBOSE` so logins are logged with the key fingerprint.
FILE:templates/access-review-report.md
# SSH key access review: {{server or fleet}} ({{date}})
Reviewer: {{name}} | Files reviewed: {{count and paths}} | Owners list: {{file, last updated}}
## Summary
- {{N}} keys in {{N}} files; {{N}} high, {{N}} medium, {{N}} low findings
- Key types: {{e.g. 9 ed25519, 2 rsa-4096, 1 rsa-1024, 1 dsa}}
- Verdict: {{clean / actions needed / urgent removals done today}}
## Actions
| # | Finding | Key (comment, fingerprint) | Owner | Action | Due | Done |
|---|---|---|---|---|---|---|
| 1 | {{K09 owner left}} | {{carol@old-macbook, SHA256:...}} | {{manager}} | Remove line | {{today}} | {{yes/no}} |
| 2 | {{K02 RSA 1024}} | {{legacy-backup, SHA256:...}} | {{ops}} | New ed25519 key on the backup host, restrict + command, then remove old | {{date}} | |
| 3 | {{K10 unknown key}} | {{SHA256:...}} | unknown | Ask in {{channel}}; comment out on {{date}}, remove on {{date}} | | |
## Removed today
- {{comment / fingerprint}} - {{reason}} - {{who confirmed}}
## Still unknown
- {{keys nobody claimed yet, and the deadline}}
## Follow-up
- Fix at the source: {{config management repo / image}}
- Next review: {{date}} (re-run `ssh_keys_audit.py --owners owners.csv --fail-on medium`)
FILE:examples/authorized_keys
# /home/deploy/.ssh/authorized_keys on web-01.example.internal (fictional demo; public keys only)
# people
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHFe7WeKd2Owa2Hh2kJr7nzgVZC8s9Ovp1f121uAPFhX alice@laptop-2026
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCnWx5TWWgt37zJmeY9/bLqaQnO0UnBNUQHVfbs5cQdeJ/f/QFHtN2tiK7p0xNF1FhZPFgRsl9UIKjQe3QSSOmX4TIu0y7wWjdfeO160ZQhlPNAh7IK8wvBvFo7g05jwI7P62B+fmvRHz0EL20n7E3fuw9HiRU77sKtdlGvKr/y8mXkFp70FFKtFmQcj53WzHEFCp6KwuJZD4YrI+rcSjULx4ZRyDNF4QJmg4jn1LcUAl7NfyV44Ow0yvZQ5a5d2gKjDbCC3//VINtJrN1eXgp13oFHzFxY3JedFCG0AjxokzIxr8zC/ATsdBPeEV15OQNxwqPb1dSQ/F8n5QznixiwkIi58h7+Zcu3QNhrZNZpjaj7rt+f2cPzMC3CQ+QYp3CmebfATT/tcq4zpVhT5nKPZHuekrxD8BLB1eqk2NNtVqG9bp12kmTcTExk9goR1dVKmGTmiKN4Y6OY5PbLRrVq/vaxBqPZsRt1nmN+tqqk36ONqhAzcSzcTnzMBI0AfzUOj4mmdWcGaJWbO70vMyjKF5gb3OxCecdhw0xwgb5JFiinPVaDZpysA/dViHouz2cBZ6xub5GEqYaitPb6EJnRZWXGAS3Ht+87lnlMTP1Xf6aa93B3b+69CRh0BtpqjDd11SFGHSxAqoGPtM7yWrA0H/mzuCDA5Sh/I5MLJx4kEw== bob@workstation
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC3+BmTPsItN0a8fWMCarZW08Kdcm2YJzCJvSc+T38xNvbJapmg4F5GCsw8jI0vuOcTn1h7WV/d0ou/8H4LNinVQ1ozTbjM3FLgXokB5GH05nXsn/uBeiARO/tqQ5/7ZGuOs0im5ubGwwzp113SgsGHQT7vihcwcDSMwYpHQcKOxSPjpN04346VuwA0hUU/CKD8VAg3/Jv4Tx8hPcXMj0iWVTEcXdhGkk9inXgJnTnGKswWvaodO4xo9zz1Ilpt1/vHSasGoDBY69Ix6YelhmQgoNRTZAGUqFR4HbYVS87jlwe2nmBnrswrqHiMphbV0AqCM0dklwiXzxxq/W4yjF9D carol@old-macbook
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBN7PNxyNXn5mvgmJcQJ5XnbF6ecut86YWirOFbgbU4FNdCM926HTQO+WiB5fVv9q4i1Z2IA8T2IlI6OzUjDR4WE= dave@tablet
sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIG51r2VHz7EbQgckgtxTHCvDkHyWF+teUInkAYa6qKV9AAAABHNzaDo= erin@yubikey
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHFe7WeKd2Owa2Hh2kJr7nzgVZC8s9Ovp1f121uAPFhX alice@laptop-2026-copy
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHunuVy30PtFkG0kzjW2DyAijGaDf4mamV1EeC1IVBe9
# automation
from="10.20.0.0/16",restrict ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPayPOBQUnoa7No6o2EaQvGV1rmdcohl25jOvTU+h3pV ci-deploy@build-runner
command="/usr/local/bin/backup-receive",no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQC0yY9ApJXN7gLq07iGKSGC5X3mT5xqBjH5XVe35ZhhZ95IGyyV4LyGuoW8W+yHUPj9XbzafPvcaa4r45fmXOY2Avj2IzMdrG3hYBO9w+urhN736J/A5+wSKFAmSShJDbRckmT1Pooph6HBM8AwG2b4iBiV97bQXjbUJoSlQHj4zQ== legacy-backup
ssh-dss AAAAB3NzaC1kc3MAAACBANGlTcoYJTC7HW0TLN7WI3su2R4/ch/LGXEXRJTWSTydXDRgvjEgHmn+2qDu6LmZf1x8KZn9r+WTJTzWVK9N+tcUJ6Cus/7pIy+K8iEfnuSRxbEL7LVWO/web5NCfsvI/ilV5c2ORtyO1LfCdk0qWk12dwb4XYaQAkrWvaNAG+nIAAAAFQCby8zJNfbNH2EiauFTOK4aNABNMwAAAIC6DSRqwEyBsbryPjv57vX3nytJNK+H9VILablLDZguhbtVtnKocmN6zXRm/LYODo/xhGOw5LK6KXA0dPBkrGj3APWwKz3GZvRb3qosyu3NK1FXQQ5N7krys09DCgc0R95jbA6AbJV7poTWQx+16tdCTQnhXQJMWEjyPR+m9zYdfwAAAIBhjRUy5w4g4qZmjef0foRn5UbVPsjioSV72yVsmz5Pu0mBRu9wMMv5U3JS3M6t12S2oy+7Ca3q4QnEqZcgOXU1K4eLFFyKQtiEz0z9py2OHV3ZJYkILYUqcSKHPugFrdWJQhZ6OFKGGVxnn5xplORbirEJgBIHCWHzfeQ23f3JnQ== nagios-check
expiry-time="20261115",restrict ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBGeb7ZdAKvDKvOOZn8CLoctScwVyQuZm3crT8em/UyR vendor-support@contractor
restrict,port-forwarding,permitopen="localhost:5432" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEoW20cIdSsPFUS4NcDnGQl9+ocB6SMvIfKBJod4aXbr db-tunnel@ops
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPzDJ/WTF2UnS6mCm0QG9h/4iTJv+pSS7e7uPGafK/II cron-sync@reports
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC7truncated-paste frank@desktop
FILE:examples/owners.csv
match,owner,status,last_review,note
alice@laptop-2026,Alice Kaya (backend),active,2026-09-14,
bob@workstation,Bob Lindqvist (SRE),active,2026-09-14,
carol@old-macbook,Carol Mendes (frontend),left,2026-03-02,left the company 2026-06-30
dave@tablet,Dave Osei (support lead),active,2025-08-20,
erin@yubikey,Erin Novak (security),active,2026-11-01,hardware key
ci-deploy@build-runner,CI pipeline (platform team),active,2026-10-05,
legacy-backup,Backup server (ops),active,2024-11-11,old backup host scheduled for replacement
vendor-support@contractor,Vendor support contract,revoked,2026-11-15,contract ended 2026-11-15
db-tunnel@ops,Ops on-call tunnel,active,2026-10-05,
FILE:scripts/ssh_keys_audit.py
#!/usr/bin/env python3
"""ssh_keys_audit.py - audit OpenSSH authorized_keys files without connecting anywhere.
Reads one or more authorized_keys files (or '-' for stdin), parses options, key type, key blob
and comment, computes the SHA256 fingerprint exactly like `ssh-keygen -lf`, measures RSA key size,
and prints findings K01-K12 (+ E01). Optional --owners CSV maps fingerprints or comments to people
so keys of people who left, unknown keys and overdue reviews are flagged too.
Python 3.8+ standard library only. Never reads private keys; never opens network connections.
Usage:
ssh_keys_audit.py FILE [FILE ...] [--owners owners.csv] [--today YYYY-MM-DD]
[--format text|md|json|csv] [--fail-on high|medium|low|none]
[--min-rsa-bits 3072] [--review-days 365]
ssh_keys_audit.py --self-test
Exit codes: 0 = nothing at or above --fail-on, 1 = findings at or above it, 2 = unreadable input.
"""
import argparse, base64, csv, datetime, hashlib, io, json, re, struct, sys
SEV_ORDER = {"high": 3, "medium": 2, "low": 1, "info": 0}
FLAGS = {
"K01": ("high", "DSA (ssh-dss) key: disabled by default since OpenSSH 7.0 and removed in OpenSSH 10.0"),
"K02": ("high", "RSA key shorter than 2048 bits"),
"K03": ("medium", "RSA key shorter than --min-rsa-bits (default 3072) but at least 2048 bits"),
"K04": ("medium", "same public key appears more than once (in one file or across files)"),
"K05": ("low", "key has no comment, so nobody can tell whose key it is"),
"K06": ("medium", "automation-looking key (comment mentions ci, deploy, backup, bot, cron, ansible...) without from= or command= restriction"),
"K07": ("high", "expiry-time option is in the past (OpenSSH already refuses it, but it is clutter and may hide a gap)"),
"K08": ("medium", "forced command= key still allows forwarding or a PTY (add restrict or no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty)"),
"K09": ("high", "owners file marks this key's owner as left/revoked"),
"K10": ("medium", "key not found in the owners file (unknown key)"),
"K11": ("low", "last review in the owners file is older than --review-days (default 365)"),
"K12": ("info", "agent forwarding or port forwarding explicitly enabled with permitopen/permitlisten - check that it is intended"),
"E01": ("medium", "line could not be parsed (bad base64, unknown type, type mismatch inside the blob)"),
}
KEY_TYPES = {"ssh-ed25519", "ssh-rsa", "ssh-dss", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521",
"sk-ssh-ed25519@openssh.com", "sk-ecdsa-sha2-nistp256@openssh.com"}
CERT_SUFFIX = "-cert-v01@openssh.com"
AUTOMATION = re.compile(r"\b(ci|cd|deploy|deployer|backup|bot|cron|ansible|jenkins|runner|github-actions|gitlab|terraform|svc|service)\b", re.I)
RESTRICT_ALL = {"no-port-forwarding", "no-agent-forwarding", "no-x11-forwarding", "no-pty"}
def split_options(s):
"""Split the leading options field of an authorized_keys line. Returns (options list, rest)."""
opts, cur, i, inq = [], "", 0, False
while i < len(s):
ch = s[i]
if ch == "\\" and inq and i + 1 < len(s):
cur += s[i:i + 2]; i += 2; continue
if ch == '"':
inq = not inq; cur += ch
elif ch == "," and not inq:
opts.append(cur); cur = ""
elif ch in " \t" and not inq:
opts.append(cur); return [o for o in opts if o], s[i:].strip()
else:
cur += ch
i += 1
raise ValueError("options field without a key")
def read_string(blob, off):
if off + 4 > len(blob):
raise ValueError("truncated blob")
(n,) = struct.unpack(">I", blob[off:off + 4])
if off + 4 + n > len(blob):
raise ValueError("truncated blob")
return blob[off + 4:off + 4 + n], off + 4 + n
def mpint_bits(b):
b = b.lstrip(b"\x00")
return 0 if not b else (len(b) - 1) * 8 + b[0].bit_length()
def parse_line(line):
"""Return dict(options, type, blob_b64, comment, bits, fingerprint) or raise ValueError."""
s = line.strip()
first = s.split(None, 1)[0]
if first in KEY_TYPES or first.endswith(CERT_SUFFIX):
options, rest = [], s
else:
options, rest = split_options(s)
parts = rest.split(None, 2)
if len(parts) < 2:
raise ValueError("missing key data")
ktype, b64 = parts[0], parts[1]
comment = parts[2].strip() if len(parts) > 2 else ""
if ktype not in KEY_TYPES and not ktype.endswith(CERT_SUFFIX):
raise ValueError("unknown key type %r" % ktype[:40])
try:
blob = base64.b64decode(b64, validate=True)
except Exception:
raise ValueError("invalid base64 key data")
inner, off = read_string(blob, 0)
if inner.decode("ascii", "replace") != ktype:
raise ValueError("key type %s does not match blob type %s" % (ktype, inner.decode("ascii", "replace")[:40]))
bits = None
if ktype == "ssh-rsa":
_e, off = read_string(blob, off)
n, off = read_string(blob, off)
bits = mpint_bits(n)
elif ktype == "ssh-dss":
p, off = read_string(blob, off)
bits = mpint_bits(p)
elif "nistp" in ktype:
bits = int(re.search(r"nistp(\d+)", ktype).group(1))
elif "ed25519" in ktype:
bits = 256
fp = "SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=")
return {"options": options, "type": ktype, "blob_b64": b64, "comment": comment, "bits": bits, "fingerprint": fp}
def opt_map(options):
m = {}
for o in options:
k, _, v = o.partition("=")
m.setdefault(k.lower(), []).append(v.strip('"') if v else True)
return m
def load_owners(path):
rows = []
with open(path, newline="", encoding="utf-8") as f:
for r in csv.DictReader(f):
rows.append({k.strip().lower(): (v or "").strip() for k, v in r.items() if k})
need = {"match", "owner", "status"}
if rows and not need <= set(rows[0]):
raise ValueError("owners CSV needs columns match,owner,status (optional: last_review,note)")
return rows
def find_owner(key, owners):
for r in owners:
m = r["match"]
if m.startswith("SHA256:") and m == key["fingerprint"]:
return r
for r in owners:
m = r["match"]
if not m.startswith("SHA256:") and m and m == key["comment"]:
return r
return None
def parse_date(s):
s = s.strip()
for fmt in ("%Y-%m-%d", "%Y%m%d", "%Y%m%d%H%M", "%Y%m%d%H%M%S"):
try:
return datetime.datetime.strptime(s, fmt).date()
except ValueError:
pass
return None
def audit(files, owners=None, today=None, min_rsa=3072, review_days=365):
today = today or datetime.date.today()
keys, flags, seen = [], [], {}
for name, text in files:
for ln, raw in enumerate(text.splitlines(), 1):
if not raw.strip() or raw.lstrip().startswith("#"):
continue
where = "%s:%d" % (name, ln)
try:
k = parse_line(raw)
except ValueError as e:
flags.append({"code": "E01", "severity": FLAGS["E01"][0], "where": where, "key": None, "detail": str(e)})
continue
k["where"] = where
keys.append(k)
om = opt_map(k["options"])
label = k["comment"] or k["fingerprint"][:20]
def add(code, detail):
flags.append({"code": code, "severity": FLAGS[code][0], "where": where, "key": label, "detail": detail})
if k["type"] == "ssh-dss":
add("K01", "ssh-dss %s bits" % k["bits"])
if k["type"] == "ssh-rsa":
if k["bits"] < 2048:
add("K02", "RSA %d bits" % k["bits"])
elif k["bits"] < min_rsa:
add("K03", "RSA %d bits < %d" % (k["bits"], min_rsa))
if k["blob_b64"] in seen:
add("K04", "same key as %s" % seen[k["blob_b64"]])
else:
seen[k["blob_b64"]] = where
if not k["comment"]:
add("K05", k["fingerprint"])
restricted = "from" in om or "command" in om
if k["comment"] and AUTOMATION.search(k["comment"]) and not restricted:
add("K06", "comment %r has no from= or command=" % k["comment"])
if "expiry-time" in om:
d = parse_date(str(om["expiry-time"][0]))
if d and d < today:
add("K07", "expired %s" % d.isoformat())
if "command" in om and "restrict" not in om and not RESTRICT_ALL <= set(om):
missing = sorted(RESTRICT_ALL - set(om))
add("K08", "forced command without " + ",".join(missing))
if {"permitopen", "permitlisten"} & set(om) or ("restrict" in om and {"port-forwarding", "agent-forwarding"} & set(om)):
add("K12", ",".join(sorted(x for x in om if x in ("permitopen", "permitlisten", "port-forwarding", "agent-forwarding"))))
if owners is not None:
o = find_owner(k, owners)
k["owner"] = o["owner"] if o else None
if o is None:
add("K10", k["fingerprint"])
else:
st = o["status"].lower()
if st in ("left", "revoked", "inactive", "offboarded"):
add("K09", "%s is %s" % (o["owner"], st))
lr = parse_date(o.get("last_review", "")) if o.get("last_review") else None
if lr is None or (today - lr).days > review_days:
add("K11", "last review %s" % (lr.isoformat() if lr else "never"))
def _w(w):
name, _, ln = w.rpartition(":")
return (name, int(ln) if ln.isdigit() else 0)
flags.sort(key=lambda f: (-SEV_ORDER[f["severity"]], f["code"], _w(f["where"])))
count = {s: sum(1 for f in flags if f["severity"] == s) for s in SEV_ORDER}
types = {}
for k in keys:
t = k["type"] + ("-%d" % k["bits"] if k["type"] == "ssh-rsa" else "")
types[t] = types.get(t, 0) + 1
summary = {"files": len(files), "keys": len(keys), "unparsed": sum(1 for f in flags if f["code"] == "E01"),
"by_type": dict(sorted(types.items())), "findings": count, "today": today.isoformat()}
return {"summary": summary, "keys": keys, "flags": flags}
def render(res, fmt):
s, out = res["summary"], []
if fmt == "json":
keys = [{k: v for k, v in x.items() if k != "blob_b64"} for x in res["keys"]]
return json.dumps({"summary": s, "keys": keys, "flags": res["flags"]}, indent=2)
if fmt == "csv":
b = io.StringIO(); w = csv.writer(b, lineterminator="\n")
w.writerow(["where", "type", "bits", "fingerprint", "comment", "owner", "options"])
for k in res["keys"]:
w.writerow([k["where"], k["type"], k["bits"], k["fingerprint"], k["comment"], k.get("owner") or "", ",".join(k["options"])])
return b.getvalue().rstrip("\n")
f = s["findings"]
head = "%d keys in %d file(s), %d unparsed line(s); findings: %d high, %d medium, %d low, %d info" % (
s["keys"], s["files"], s["unparsed"], f["high"], f["medium"], f["low"], f["info"])
types = ", ".join("%s x%d" % kv for kv in s["by_type"].items())
if fmt == "md":
out += ["## SSH authorized_keys audit (%s)" % s["today"], "", "- " + head, "- key types: " + types, "",
"| Sev | Code | Where | Key | Detail |", "|---|---|---|---|---|"]
out += ["| %s | %s | %s | %s | %s |" % (x["severity"], x["code"], x["where"], x["key"] or "-", x["detail"].replace("|", "/")) for x in res["flags"]]
out += ["", "### Keys", "", "| Where | Type | Bits | Fingerprint | Comment | Owner |", "|---|---|---|---|---|---|"]
out += ["| %s | %s | %s | `%s` | %s | %s |" % (k["where"], k["type"], k["bits"], k["fingerprint"], k["comment"] or "-", k.get("owner") or "-") for k in res["keys"]]
return "\n".join(out)
out += ["SSH authorized_keys audit (%s)" % s["today"], "- " + head, "- key types: " + types, "", "Keys"]
for k in res["keys"]:
out.append(" %-28s %-20s %5s %s %s%s" % (k["where"], k["type"][:20], k["bits"], k["fingerprint"][:27] + "...", k["comment"] or "(no comment)",
(" [" + (k.get("owner") or "unknown") + "]") if "owner" in k else ""))
out += ["", "Findings"]
if not res["flags"]:
out.append(" none")
for x in res["flags"]:
out.append(" %-6s %s %-28s %-24s %s" % (x["severity"].upper(), x["code"], x["where"], (x["key"] or "-")[:24], x["detail"]))
return "\n".join(out)
def self_test():
import os, tempfile
def blob(*parts):
return base64.b64encode(b"".join(struct.pack(">I", len(p)) + p for p in parts)).decode()
ed = blob(b"ssh-ed25519", bytes(range(32)))
ed2 = blob(b"ssh-ed25519", bytes(range(1, 33)))
rsa1k = blob(b"ssh-rsa", b"\x01\x00\x01", b"\x00" + b"\xc3" + b"\x11" * 127)
rsa2k = blob(b"ssh-rsa", b"\x01\x00\x01", b"\x00" + b"\xc3" + b"\x22" * 255)
dss = blob(b"ssh-dss", b"\x00" + b"\x99" * 128, b"\x88" * 20, b"\x77" * 128, b"\x66" * 128)
text = "\n".join([
"# comment line", "",
"ssh-ed25519 %s alice@laptop" % ed,
'from="10.0.0.0/8",no-agent-forwarding ssh-ed25519 %s ci-deploy@runner' % ed2,
"ssh-rsa %s old" % rsa1k,
"ssh-rsa %s mid@host" % rsa2k,
"ssh-dss %s legacy" % dss,
"ssh-ed25519 %s" % ed,
'command="/usr/bin/backup.sh",no-pty ssh-ed25519 %s backup-bot' % blob(b"ssh-ed25519", b"\x05" * 32),
'expiry-time="20250101",restrict ssh-ed25519 %s temp@contractor' % blob(b"ssh-ed25519", b"\x06" * 32),
"ssh-ed25519 !!!notbase64 bad",
"ssh-rsa %s mismatch" % ed,
'restrict,port-forwarding,permitopen="db:5432" ssh-ed25519 %s tunnel@ops' % blob(b"ssh-ed25519", b"\x07" * 32),
"ssh-ed25519 %s deploy@ci" % blob(b"ssh-ed25519", b"\x08" * 32)])
owners = [{"match": "alice@laptop", "owner": "Alice", "status": "active", "last_review": "2026-10-01"},
{"match": "old", "owner": "Olga", "status": "left", "last_review": "2024-01-01"}]
r = audit([("t", text)], owners=owners, today=datetime.date(2026, 12, 3))
codes = [f["code"] for f in r["flags"]]
checks = [
("10 keys parsed", r["summary"]["keys"] == 10),
("2 unparsed", codes.count("E01") == 2),
("rsa 1024 bits", any(k["bits"] == 1024 for k in r["keys"])),
("rsa 2048 bits", any(k["bits"] == 2048 for k in r["keys"])),
("K01 dss", "K01" in codes), ("K02 short rsa", codes.count("K02") == 1), ("K03 2048", codes.count("K03") == 1),
("K04 duplicate", codes.count("K04") == 1), ("K05 no comment", codes.count("K05") == 1),
("K06 unrestricted automation only deploy@ci", [f["key"] for f in r["flags"] if f["code"] == "K06"] == ["deploy@ci"]),
("K07 expired", codes.count("K07") == 1), ("K08 forced command partial", codes.count("K08") == 1),
("K09 left", codes.count("K09") == 1), ("K10 unknown", codes.count("K10") == 8),
("K11 stale review", codes.count("K11") == 1), ("K12 permitopen", codes.count("K12") == 1),
("options with quoted comma", split_options('from="a,b",no-pty ssh-ed25519 X')[0] == ['from="a,b"', "no-pty"]),
("fingerprint format", r["keys"][0]["fingerprint"].startswith("SHA256:") and "=" not in r["keys"][0]["fingerprint"]),
("sorted by severity", [SEV_ORDER[f["severity"]] for f in r["flags"]] == sorted([SEV_ORDER[f["severity"]] for f in r["flags"]], reverse=True)),
("md render", render(r, "md").startswith("## SSH authorized_keys audit")),
("csv render", render(r, "csv").splitlines()[0].startswith("where,type,bits")),
]
bad = [n for n, ok in checks if not ok]
if bad:
print("self-test FAILED:", ", ".join(bad)); print(codes); return 1
print("self-test OK: %d checks" % len(checks)); return 0
def main(argv=None):
ap = argparse.ArgumentParser(description="Audit OpenSSH authorized_keys files (offline, stdlib only).")
ap.add_argument("files", nargs="*", help="authorized_keys files, or - for stdin")
ap.add_argument("--owners", help="CSV with columns match,owner,status[,last_review,note]; match = SHA256 fingerprint or exact comment")
ap.add_argument("--today", help="date for expiry/review checks (YYYY-MM-DD), default today")
ap.add_argument("--format", choices=["text", "md", "json", "csv"], default="text")
ap.add_argument("--fail-on", choices=["high", "medium", "low", "none"], default="high")
ap.add_argument("--min-rsa-bits", type=int, default=3072)
ap.add_argument("--review-days", type=int, default=365)
ap.add_argument("--self-test", action="store_true")
a = ap.parse_args(argv)
if a.self_test:
return self_test()
if not a.files:
ap.error("give at least one authorized_keys file (or --self-test)")
files = []
try:
for p in a.files:
files.append(("stdin", sys.stdin.read()) if p == "-" else (p, open(p, encoding="utf-8", errors="replace").read()))
owners = load_owners(a.owners) if a.owners else None
except (OSError, ValueError) as e:
print("error: %s" % e, file=sys.stderr); return 2
today = parse_date(a.today) if a.today else None
if a.today and today is None:
print("error: --today must be YYYY-MM-DD", file=sys.stderr); return 2
res = audit(files, owners, today, a.min_rsa_bits, a.review_days)
print(render(res, a.format))
if a.fail_on == "none":
return 0
lim = SEV_ORDER[a.fail_on]
return 1 if any(SEV_ORDER[f["severity"]] >= lim and f["severity"] != "info" for f in res["flags"]) else 0
if __name__ == "__main__":
sys.exit(main())