Skip to main content

keywatch: find SSH keys that still work and should not.

keywatch scans authorized_keys across your machines, maps every key to a person (or "unknown"), and lists who can still get in, with a removal list of candidates for you to review and apply by hand.

pip install keywatch && keywatch init

Needs Python 3.10 or newer. Standard library only. keywatch NEVER deletes or modifies any authorized_keys file. There is no --apply flag in v1, by design.

Real output from the shipped example fleet (run in a temporary folder; the top of the report is shown, the rest lists each flagged key and the removal list):

$ keywatch scan --dir ex/fleet --mapping ex/mapping.json --departed ex/departed.txt --no-state
keywatch scan: 5 keys across 2 machines, 2 users (5 flagged, 0 parse errors, 0 source notes)
scan record written: ./keywatch-scan.json
next: keywatch report

$ keywatch report
keywatch report: 5 keys across 2 machines, 2 users
flags: 5 keys flagged, 0 parse errors, 0 source notes

who can still get in (per human):
  alice: 3 key(s) across 2 machine(s), 3 flagged
  legacy: 1 key(s) across 1 machine(s), 1 flagged
  mallory: 1 key(s) across 1 machine(s), 1 flagged

...
  • Finds access that outlived the person. Deprovisioning removes the account but misses authorized_keys; ex-staff, ex-contractors and forgotten deploy keys keep working logins. keywatch flags departed owners, unknown owners, shared, weak, aged and expired keys.
  • Checks before you delete. keywatch verify re-reads every file behind the removal list and tells you whether each listed line number is still right, because line numbers shift and fingerprints do not.
  • Keeps the review going. keywatch diff shows access drift between two scans; keywatch validate checks your own mapping and departed files.

Release PyPI License Python


Quickstart

pip install keywatch           # or, from a checkout: pip install .
keywatch init                  # starter mapping/departed files + the guided steps
keywatch scan --dir ./fleet    # or --local, --file, --host user@host
keywatch report                # who can still get in + the removal list
keywatch verify                # BEFORE you apply the removal list by hand

Without installing, from a checkout: PYTHONPATH=. python -m keywatch --version. No dependencies, no network calls except the SSH connections you explicitly ask for, no telemetry, no phone-home.

Limits up front

  • Reads and reports only. No deletion, no --apply in v1.
  • Keys served by AuthorizedKeysCommand or LDAP never appear in a file, so keywatch cannot see them.
  • authorized_keys has no per-key timestamps, so the first scan never flags anything as aged (see The age limitation).
  • Windows is not a supported platform (see What keywatch does NOT do).
  • Nothing was tested here against a real multi-host fleet over real SSH (see Live vs fixture).

Docs: CHANGELOG, REVIEW, issues.

Usage

# First time here: starter files + the guided workflow
keywatch init

# Inventory a fleet-collected tree (machine/user/authorized_keys)
keywatch scan --dir ./fleet \
  --mapping ./mapping.json --departed ./departed.txt

# One explicit file, a local machine, remote hosts (your own SSH)
keywatch scan --file ./keys.txt --machine web1 --user deploy
keywatch scan --local
keywatch scan --host deploy@web1 --host deploy@db1
keywatch scan --hosts-file hosts.txt   # one user@host per line, # comments

# Render the report + removal list from the last scan
keywatch report

# BEFORE applying the removal list by hand: re-check every entry
# against the files as they are now (read-only — never modifies)
keywatch verify

# Next month: what changed since the last scan (access drift)
keywatch diff last-scan.json this-scan.json

# Check your own homework: mapping/departed file hygiene
keywatch validate --mapping ./mapping.json --departed ./departed.txt

# Machine-readable everywhere
keywatch scan --dir ./fleet --json
keywatch report --json
keywatch verify --json
keywatch diff old.json new.json --json

Exit codes: 0 clean (no flags, no unparseable lines) / verify safe / no drift / validate clean, 1 flags found, or scan could not parse some lines (they were not audited; a warning goes to stderr) / verify unsafe / drift found / validate issues, 2 error (nothing to scan, bad mapping/departed/ state file, unreadable scan record).

Verify before you delete — the staleness problem, stated plainly

The removal list names line numbers from scan time. Line numbers shift when a file changes; fingerprints do not. If you apply a stale list by line number alone, you can delete the WRONG key. keywatch verify closes that hole mechanically: it re-reads every file behind a flagged key and reports, per entry:

  • VERIFIED — the fingerprint still sits on the listed line. Safe to apply exactly as listed.
  • MOVED — the fingerprint is still in the file, but on different line(s). Do NOT apply the old line number — re-scan and use the new list.
  • GONE — the fingerprint is no longer in the file. Nothing to do; the key is already removed.
  • UNREADABLE / REMOTE_ERROR — the file could not be re-read. Do NOT apply blindly; the entry cannot be confirmed.

Verify exits 0 only when every entry is VERIFIED or GONE. Any MOVED or unverifiable entry means: do not apply, re-scan first. Verify never writes anything — no file modification, no state update, no scan record change. Scan records also carry each file's SHA-256 at scan time, so a changed file is visible even when the listed line is still valid.

Scheduling is a documented cron/systemd example, not a built service — run keywatch scan weekly and keep the scan records:

0 3 * * 0 cd /opt/keywatch && keywatch scan --dir ./fleet \
  --mapping ./mapping.json --departed ./departed.txt

The recurring review, by hand: diff + validate

A one-off audit rots. Two commands keep it alive without a dashboard, a scheduler, or an alerting service (those are the team tier — the recurring review itself is free):

  • keywatch diff old.json new.json compares two scan records by grant (machine, user, fingerprint — line numbers and files are NOT identity, because lines shift). It reports access gained, access removed, flag changes on continuing grants (a key that quietly became DEPARTED or WEAK), and owner changes. Exit 0 means no drift; exit 1 means something changed and the report names exactly what.
  • keywatch validate --mapping … --departed … checks the operator's own files, because the mapping file is the moat and a moat nobody checks rots: malformed fingerprint keys that could never match a scanned key, malformed fingerprint entries in the departed file, and the most common staleness of all — a departed human who is STILL listed as a mapping value, so their keys keep resolving to a live human instead of flagging DEPARTED.

The report's per-human section helps with the "who has access to what" question auditors ask (it is not a compliance attestation): it lists machines per human ("alice: 3 key(s) across 2 machine(s), 3 flagged"), and a first-seen age-bucket line (<90d, 90-365d, >365d) shows the age shape of the estate at a glance.

Key-to-human mapping

Resolution order per key:

  1. Mapping file (explicit fingerprint → human, JSON). Always wins.
  2. Key comment (provisional owner — comments are often usernames, but anyone can write anything in a comment, so the report records the source as comment).
  3. Certificate principal (for cert keys — principals are issued by the CA, so they are stronger evidence than a free-text comment, but still below an explicit mapping entry).
  4. "unknown" — a flag, never silently dropped.

A mapping entry that disagrees with the comment is NOT silently resolved: OWNER_CONFLICT flags it. The rule is deliberately narrow — same name case-insensitively, or same local part (alice vs alice@laptop), is the SAME person, the normal pattern; only genuinely different names conflict, meaning one of the two is stale or the comment is lying.

Departed list: a plain text file, one human per line (# comments ignored) — or a fingerprint in SHA256:... / MD5:... form, which matches by fingerprint instead of by name. A key flags DEPARTED if its resolved owner, raw comment, cert principal, or fingerprint matches a departed entry (names case-insensitive). Fingerprint matching matters: a departed person's key with a scrubbed comment still flags.

Mapping staleness is surfaced, not hidden: mapping entries whose fingerprints are not observed in a scan appear as MAPPING_UNOBSERVED notes (a scan may be partial, so these are notes, not flags — the operator cleans the mapping file).

Flags

Flag Meaning
UNKNOWN_OWNER No mapping match, no comment, no cert principal.
OWNER_CONFLICT Mapping names one human, comment names a genuinely different one.
DEPARTED Owner, comment, cert principal, or fingerprint is on the departed list.
DUPLICATE Same fingerprint under two or more distinct users (shared key). The detail names the shape: one key under multiple accounts on ONE machine is a lateral-movement risk; sharing across machines is fleet-wide sharing. Same user on several machines is normal use, not flagged.
DUPLICATE_LINE Same key twice in one file, or in both authorized_keys and authorized_keys2 of one user.
WRITABLE_BY_OTHERS --local/--dir only, not on Windows: the file or its directory is group/world-writable, or (--local) owned by someone other than the user or root. Anyone with write access can add keys, and sshd StrictModes may ignore the file. A partial check: keywatch does not walk every parent directory the way sshd does, and cannot stat files read over --host.
AGED First seen longer ago than --max-age-days (default 365).
WEAK DSA, or RSA below 2048 bits.
CERT_EXPIRED Certificate validity window has ended (sshd rejects the key — dead access, not live access).
CERT_NOT_YET_VALID Certificate validity window has not started yet.
EXPIRED An expiry-time option has passed (sshd rejects the key).
EXPANDED_ACCESS Key carries capability-expanding options (permitopen, forwarding, environment, tunnel) — it can do more than a plain login.
RESTRICTED Key carries only constraining options (command=, restrict, from=, no-*) — it cannot do a plain login. Informational, but named.
HAS_OPTIONS Key carries options fitting neither bucket (expiry-time not yet reached, cert-authority, unrecognized) — still named, never silently treated as plain.

Cert keys also record key ID, principals, and the validity window in the scan record, parsed from the real cert blob (verified against ssh-keygen -L output). A cert whose fields cannot be parsed records cert: null — unknown validity, never silently treated as valid.

Example report (departed ex-contractor key)

keywatch report: 1 keys across 1 machines, 1 users
flags: 1 keys flagged, 0 parse errors, 0 source notes

who can still get in (per human):
  alice@laptop: 1 key(s), 1 flagged

flagged keys:
  [DEPARTED] SHA256:y0C4dkXSZUa/mN0jlAskaO60Zf2VaE2GN8pco5XlVGc
      (ssh-ed25519, comment 'alice@laptop')
      machine web9, user deploy,
      file /tmp/kw-demo/fleet/web9/deploy/authorized_keys, line 1
      DEPARTED: owner 'alice@laptop' is on the departed list

removal list (candidates: review each, apply manually — keywatch never deletes):
  web9 deploy /tmp/kw-demo/fleet/web9/deploy/authorized_keys
    line 1 SHA256:y0C4dkXSZUa/mN0jlAskaO60Zf2VaE2GN8pco5XlVGc [DEPARTED]

The age limitation, stated plainly

authorized_keys carries no per-key timestamps, so file mtime is only a weak proxy: a file rewrite refreshes every line's mtime at once, and a copied file keeps none of the original timing. keywatch therefore tracks first-seen per fingerprint in a local state file (--state, mode 0o600). Consequence: the FIRST scan never flags anything as aged, because everything is new to the tool. Age flags become meaningful on the second and later scans. Anyone offering instant age answers from mtime alone is selling a proxy, not a clock. --no-state skips age tracking entirely (no AGED flags, no guessing).

Two honesty guards on the clock itself: a corrupt state file is an error, never silently replaced (resetting first-seen dates would erase every age flag); and a MISSING state file with a previous scan record on disk warns loudly (STATE_RESET) instead of silently treating every key as new. --prune-state drops first-seen entries absent from the current scan — opt-in only, and only correct when the scan covers the full fleet (on a partial scan, absence means "not scanned", not "removed").

Remote hosts — what is and is not covered

--host uses the operator's existing SSH in BatchMode (no password prompts, no hangs). StrictHostKeyChecking=accept-new accepts an unknown host key on first contact but REFUSES a changed host key: a host-key change fails the collection loudly instead of silently talking to a different machine. --remote-path overrides the default ~/.ssh/authorized_keys and ~/.ssh/authorized_keys2 (read with one ssh call per file) for hosts whose sshd uses a non-standard AuthorizedKeysFile; paths containing shell metacharacters are refused outright rather than quoted into a different meaning. A --host value starting with - (for example -oProxyCommand=..., which ssh would treat as an option and run locally) is refused with exit 2 (a --hosts-file line too, named by line number), and the ssh call puts -- before the host.

authorized_keys2 is in OpenSSH's compiled-in default AuthorizedKeysFile (some distributions' sshd_config drop it) and is a known place to hide a key, so --local, --dir and --host read it alongside authorized_keys (a missing authorized_keys2 is not an error). The same key for the same user in both files is flagged DUPLICATE_LINE: removing it from one file leaves access.

What keywatch does NOT see, stated plainly: keys served by AuthorizedKeysCommand or LDAP/centralized directories never appear in an authorized_keys file, so a file scan cannot inventory them. If your fleet provisions keys centrally, keywatch covers the file-based remainder, not the whole estate.

Safety rules

  • Reads and reports only. No deletion, no modification, no --apply in v1. The removal list is verified (keywatch verify) before the operator applies it by hand.
  • Public key material only. keywatch reads authorized_keys files. It never reads, parses, or touches private keys (~/.ssh/id_*, *.pem, agent material).
  • No full key strings in output. Reports use fingerprints + comments + key types — enough to identify a key, never a dump of key material.
  • Reports stay local. Scan records and reports are written with mode 0o600: fingerprints plus comments can identify people and machines. Nothing is sent or shared. Stdout output is the operator's responsibility once piped elsewhere — do not pipe a report into a shared log or chat.

Live vs fixture — what was actually tested here

This sandbox has no fleet and no real authorized_keys files (--local correctly exits 2: nothing to scan). So:

  • Live-tested: the full parser, mapper, flagger, and report engine against real ssh-keygen key material (fingerprints verified against ssh-keygen -lf); certificate parsing against real CA-signed ssh-keygen certs (key ID, principals, validity windows match ssh-keygen -L); the shipped example fleet (examples/fleet/) scanned end-to-end via the real CLI; verify end-to-end (verified / moved / gone / unreadable shapes); the remote path mechanics via a stub ssh binary (proves command construction + stdout parsing — honestly labeled, not a real SSH connection); a venv install check.
  • Fixture-driven: multi-machine fleet scans, departed matches, duplicate shapes, weak types, options fields, aged logic via backdated state.
  • Not tested here: a real multi-host fleet scan over real SSH (needs the operator's existing SSH access to real hosts) and a real local multi-user machine. On a real host, --local scans every readable user's authorized_keys; --host uses the operator's existing SSH in BatchMode (no password prompts).

What's new in v0.3.0 (superiority iteration: panel + Magnates)

  • keywatch init — starter mapping/departed example files + the guided first-audit workflow. Cold start in minutes, not a README spelunk. (Writes *.example files only — an example must never silently become the operator's real mapping.)
  • keywatch diff — access drift between two scans by grant (machine, user, fingerprint): gained, removed, flag changes, owner changes. The recurring review, by hand, with JSON for tooling.
  • keywatch validate — mapping/departed hygiene: bad fingerprint forms, departed humans still mapped.
  • Report upgrades: per-human machine rollup (SOC 2: who, and to what) and first-seen age buckets.
  • Efficiency, measured: scan of 10,000 keys / 200 files / 500 departed entries went 2.08s → 0.58s (departed list now split once per scan, not once per key); verify of 2,000 entries in one file went 34.0s → 25ms (one read, one parse, one fingerprint index per file per run — the first fix attempt cached reads but still re-parsed per entry, and the perf harness caught it before it shipped).
  • Error messages now say what to DO next (scan with no source points at init; missing scan records point at scan; mapping errors point at validate).
  • Every v0.2.0 trust guarantee preserved: verify gate, never-modify, 0o600 outputs, public-keys-only, no telemetry, no phone-home, stdlib-only.

Competitive position, stated honestly

Enterprise PAM wins on enforcement (it actually revokes), centralized dashboards, and LDAP/centralized key visibility — and costs enterprise money for enterprise buyers. ssh-audit audits sshd config and host keys, not authorized_keys inventory — complementary, not competitive.

keywatch is not the only authorized_keys auditor. Two free tools overlap with it:

  • ssh_keyaudit_fleet_key_inventory.py (DEV post): stdlib, fleet inventory over BatchMode SSH, an owner file with offboarded/service status classes, weak-key flags, cross-host duplicates and a run-to-run diff. Its owner status classes are something keywatch does not have.
  • audit-ssh-keys (single host): grades host keys, authorized_keys and the private keys in ~/.ssh, and replicates sshd StrictModes (files sshd would ignore). keywatch does not check private keys and is single-purpose on authorized_keys. Its StrictModes check is fuller than keywatch's WRITABLE_BY_OTHERS, which looks only at the file and its directory.

What keywatch has that neither has: the read-only verify gate before you remove anything, per-file SHA-256 recorded at scan time, departed-by-fingerprint (matches even when the comment was scrubbed), certificate validity flags, and mapping hygiene checks (validate). keywatch still loses on enforcement, LDAP/central visibility, and fleet discovery — those are the team tier and the enterprise line, not gaps the free CLI should chase by becoming a dashboard.

What's new in v0.2.0 (panel + Magnates loop)

  • keywatch verify — the read-only staleness gate for the removal list (VERIFIED / MOVED / GONE / UNREADABLE / REMOTE_ERROR), plus per-file SHA-256 recorded at scan time.
  • Options taxonomy: EXPANDED_ACCESS vs RESTRICTED vs HAS_OPTIONS, plus expiry-time parsing with an EXPIRED flag.
  • Certificate parsing: key ID, principals, validity window; CERT_EXPIRED / CERT_NOT_YET_VALID flags; principals as an owner source.
  • OWNER_CONFLICT (narrow rule: same local part is the same person), departed-by-fingerprint, mapping-staleness notes.
  • Age-clock guards: STATE_RESET warning, opt-in --prune-state.
  • --remote-path for non-standard AuthorizedKeysFile; host-key-change behavior documented.
  • DUPLICATE detail now names the shape (lateral movement on one machine vs sharing across machines).

What keywatch does NOT do

  • Auto-delete or --apply (future, reviewed, with backups).
  • Dashboards, built schedulers, alerting, team tier (C$19/mo ESTIMATE) — the recurring review itself (diff) is free; scheduling and alerting it are the team tier.
  • Same-user duplicate detection across different files on one machine (only cross-user duplicates and same-file duplicate lines are flagged).
  • Native fleet discovery (no agent, no inventory API — you bring the files or the SSH access).
  • Keys served by AuthorizedKeysCommand / LDAP (invisible to any file scan).
  • Windows support. The package imports on Windows and --file / --dir scans work there, but it is not a supported platform: --local finds nothing (no /etc/passwd), output files do not get POSIX 0o600 modes, and the stub-ssh and file-mode tests are skipped.

Bundle story

keywatch is part of the Calas Automations small-tool line; licwatch, for example, checks dependency licenses.


Made by Calas Automations (CAL-us). Need help? Call Cara 431-244-9026.

Metadata

Release files for keywatch 0.3.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for keywatch 0.3.3
File Size Uploaded Provenance Actions
keywatch-0.3.3.tar.gz 70.2 kB Without provenance Details for keywatch-0.3.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for keywatch 0.3.3
File Interpreter ABI Platform Actions
keywatch-0.3.3-py3-none-any.whl Python 3 none any Details for keywatch-0.3.3-py3-none-any.whl

Total release size: 116.2 kB

Release files / keywatch-0.3.3.tar.gz

Download URL keywatch-0.3.3.tar.gz
Size 70.2 kB
Tags Source
SHA-256 checksum
How to use checksums
d690d0d003e3ae250a13313080bd54542957faf56d62bc2939daa6c2ddd07c20
BLAKE2b-256 checksum
How to use checksums
03f0c17913f438304c2a1105ada6aab3ff5687520be02866bc0e1637768ef4dc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Release files / keywatch-0.3.3-py3-none-any.whl

Download URL keywatch-0.3.3-py3-none-any.whl
Size 46.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4fdcec49a80df3346c670f2b4f99e1d516782d741dbda3db58ea87138f87d181
BLAKE2b-256 checksum
How to use checksums
aacc3add466041e36270f110dafa39ae42516fa7eedc1f1b017b9f73fa1b6d51
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.10

Security for keywatch 0.3.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.3.3 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page