I wanted to disable password authentication on a box last month. The sshd_config changes took 30 seconds — what stopped me was the six user accounts with shared SSH keys plus a RSA-1024 leftover from 2016 that I could not trace. SSH authorized keys are invisible until you audit them. This script inventories every ~/.ssh/authorized_keys on the system, decodes each key inside the file (no subprocess calls to ssh-keygen), computes fingerprints, flags weak algorithms, catches duplicates shared across accounts, and exits 1 on findings so your cron monitor fires a ticket.
OpenSSH Manual · sshd(8) · authorized_keys(5)
Requirements:
- Python 3.9+ (stdlib only — no pip deps)
- Read access to /etc/passwd and
.ssh/authorized_keys - A cron wrapper to capture the exit code
The script parses passwd, resolves each home, reads authorized_keys (with continuation-line support), splits options from the key material, decodes the SSH public-key blob with pure Python (length-prefixed fields), and flags the findings. Full source:
#!/usr/bin/env python3
"""
SSH Authorized Keys Auditor
Inventory every ~/.ssh/authorized_keys across system users.
Flags weak keys (RSA < 2048, DSA), missing comments,
duplicate keys shared between accounts, and documents
restrictive options (from=, command=).
Exit 1 for cron alerting when findings exist.
Usage:
python3 ssh_keys_audit.py # audit real system
python3 ssh_keys_audit.py --passwd keylab.passwd --home-prefix /root/keylab
python3 ssh_keys_audit.py --json # machine-readable output
"""
import argparse, base64, hashlib, json, os, struct, sys
from collections import defaultdict
from pathlib import Path
# Known SSH algorithm prefixes
KNOWN_KEY_TYPES = frozenset({
'ssh-rsa', 'ssh-dss', 'ssh-ed25519',
'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521',
'[email protected]', '[email protected]',
})
CURVE_BITS = {'nistp256': 256, 'nistp384': 384, 'nistp521': 521}
def fingerprint_pubkey(raw):
"""SHA256 fingerprint from raw SSH public key bytes."""
h = hashlib.sha256(raw).digest()
return 'SHA256:' + base64.b64encode(h).decode().rstrip('=')
def decode_key(b64key):
"""Return (algorithm, bits, fingerprint, error_string or None)."""
try:
raw = base64.b64decode(b64key)
except Exception as e:
return None, 0, '', f'base64 decode failed: {e}'
try:
pos = 0
hdr_len = struct.unpack('>I', raw[pos:pos+4])[0]; pos += 4
alg = raw[pos:pos+hdr_len].decode('utf-8', errors='replace'); pos += hdr_len
fp = fingerprint_pubkey(raw)
if alg.startswith('ssh-rsa'):
e_len = struct.unpack('>I', raw[pos:pos+4])[0]; pos += 4
pos += e_len # skip exponent
n_len = struct.unpack('>I', raw[pos:pos+4])[0]; pos += 4
n = int.from_bytes(raw[pos:pos+n_len], 'big')
return alg, n.bit_length(), fp, None
elif alg == 'ssh-dss':
p_len = struct.unpack('>I', raw[pos:pos+4])[0]; pos += 4
p = int.from_bytes(raw[pos:pos+p_len], 'big')
return alg, p.bit_length(), fp, None
elif alg == 'ssh-ed25519':
k_len = struct.unpack('>I', raw[pos:pos+4])[0]; pos += 4
return alg, k_len * 8, fp, None # 32 bytes → 256 bits
elif alg.startswith('ecdsa-sha2-'):
c_len = struct.unpack('>I', raw[pos:pos+4])[0]; pos += 4
curve = raw[pos:pos+c_len].decode(); pos += c_len
bits = CURVE_BITS.get(curve, 0)
return alg, bits, fp, None
elif alg.startswith('sk-'):
# Security key: ed25519 or ecdsa
k_len = struct.unpack('>I', raw[pos:pos+4])[0]; pos += 4
return alg, k_len * 8, fp, None
else:
return alg, 0, fp, 'unknown key type'
except (IndexError, struct.error, ValueError, UnicodeDecodeError) as e:
return None, 0, '', f'parse error: {e}'
def parse_auth_keys(path):
"""Parse an authorized_keys file, returning (flags, entries) list."""
entries = []
text = path.read_text(errors='replace')
# Join continuation lines (backslash-newline)
text = text.replace('\\\n', '')
lines = text.splitlines()
for line in lines:
line = line.strip()
if not line or line.startswith('#'):
continue
# Split: options KEYTYPE BASE64 COMMENT...
tokens = line.split()
if not tokens:
continue
# Find first token that is a known key type
key_start = None
for i, tok in enumerate(tokens):
if tok in KNOWN_KEY_TYPES:
key_start = i
break
if key_start is None:
# Try heuristic: starts with a known key-type prefix
for i, tok in enumerate(tokens):
if any(tok.startswith(k) for k in KNOWN_KEY_TYPES):
key_start = i
break
if key_start is None:
entries.append({'flags': 'PARSE_ERR', 'alg': '', 'bits': 0,
'fp': '', 'comment': line[:80]})
continue
options = ' '.join(tokens[:key_start]) if key_start > 0 else ''
key_type = tokens[key_start]
b64 = tokens[key_start + 1] if len(tokens) > key_start + 1 else ''
comment = ' '.join(tokens[key_start + 2:]) if len(tokens) > key_start + 2 else ''
alg, bits, fp, err = decode_key(b64)
flags = []
if err:
flags.append(f'DECODE_ERR ({err})')
else:
if alg in ('ssh-dss',):
flags.append('WEAK_DSA')
elif alg.startswith('ssh-rsa') and bits < 2048:
flags.append(f'WEAK_{bits}bit')
if not comment:
flags.append('NOCOMMENT')
if options:
opts_list = []
if 'from=' in options:
opts_list.append('from=')
if 'command=' in options:
opts_list.append('command=')
if 'no-agent-forwarding' in options:
opts_list.append('restrict-agent')
if 'no-pty' in options:
opts_list.append('no-pty')
if 'restrict' in options or 'restricted' in options:
opts_list.append('restrict')
if opts_list:
flags.append(','.join(opts_list))
entries.append({
'flags': '+'.join(flags) if flags else 'OK',
'alg': alg or '',
'bits': bits,
'fp': fp or '',
'comment': comment or '',
'options': options or '',
})
return entries
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--passwd', default='/etc/passwd')
ap.add_argument('--home-prefix', default='',
help='Prepend to home paths (for sandbox testing)')
ap.add_argument('--json', action='store_true',
help='JSON-only output for downstream tools')
args = ap.parse_args()
pwd_file = Path(args.passwd)
passwd_users = []
for line in pwd_file.read_text().splitlines():
if not line or line.startswith('#'):
continue
parts = line.split(':')
if len(parts) >= 7:
uid = int(parts[2])
home = parts[5]
shell = parts[6]
# Skip system non-login or root (root is audited separately)
if uid == 0: # root handled as a special case
continue
passwd_users.append({
'user': parts[0],
'uid': uid,
'home': home,
'shell': shell,
})
# Also audit root if in /etc/passwd
for line in pwd_file.read_text().splitlines():
if line.startswith('root:'):
parts = line.split(':')
passwd_users.append({
'user': 'root', 'uid': 0,
'home': parts[5],
'shell': parts[6],
})
break
results = []
total_keys = 0
flagged_count = 0
user_key_fps = defaultdict(set) # fp → set of users
duplicates = []
for u in passwd_users:
home = Path(args.home_prefix + u['home'])
ak_path = home / '.ssh' / 'authorized_keys'
if not ak_path.exists():
results.append({
'user': u['user'],
'uid': u['uid'],
'home': str(home),
'key_count': 0,
'status': 'NO_AUTH_KEYS_DIR',
'entries': [],
})
continue
if ak_path.stat().st_size == 0:
results.append({
'user': u['user'],
'uid': u['uid'],
'home': str(home),
'key_count': 0,
'status': 'EMPTY_AUTH_KEYS',
'entries': [],
})
continue
entries = parse_auth_keys(ak_path)
key_count = len(entries)
total_keys += key_count
status = 'OK'
for e in entries:
if e['flags'] != 'OK' and not e['flags'].startswith('DECODE_ERR'):
status = 'FLAGGED'
flagged_count += 1
if e['fp'] and e['fp'].startswith('SHA256:'):
user_key_fps[e['fp']].add(u['user'])
results.append({
'user': u['user'],
'uid': u['uid'],
'home': str(home),
'key_count': key_count,
'status': status,
'entries': entries,
})
# Cross-check duplicates
for fp, users in user_key_fps.items():
if len(users) > 1:
duplicates.append({
'fingerprint': fp,
'shared_by': sorted(users),
})
exit_code = 1 if (flagged_count > 0 or len(duplicates) > 0) else 0
if args.json:
out = {
'total_users_scanned': len(results),
'total_keys': total_keys,
'flagged_keys': flagged_count,
'duplicate_fingerprints': len(duplicates),
'duplicates': duplicates,
'exit_code': exit_code,
'accounts': [],
}
for r in results:
acct = {
'user': r['user'], 'uid': r['uid'],
'home': r['home'], 'key_count': r['key_count'],
'status': r['status'],
'keys': [
{'fp': e['fp'], 'alg': e['alg'], 'bits': e['bits'],
'comment': e['comment'], 'flags': e['flags'],
'options': e['options']}
for e in r['entries']
],
}
out['accounts'].append(acct)
print(json.dumps(out, indent=2))
sys.exit(exit_code)
# Human-readable table
header = f"{'User':<10} {'UID':>5} {'Keys':>4} {'Alg':<20} {'Bits':>5} {'Flags'}"
sep = '-' * len(header)
print('=== SSH Authorized Keys Audit Report ===')
print()
for r in results:
if r['key_count'] == 0:
print(f"{r['user']:<10} {r['uid']:>5} 0 (no authorized_keys)"
f"{' [NO-AUTH]':>20}")
else:
first_entry = True
for e in r['entries']:
alg_short = e['alg'].replace('ssh-', '').replace('ecdsa-sha2-', 'ecdsa-')
bits_str = str(e['bits']) if e['bits'] else '?'
fp_short = e['fp'][:12] + '...' if e['fp'] else '-'
if first_entry:
print(f"{r['user']:<10} {r['uid']:>5} {len(r['entries']):>4} "
f"{alg_short:<20} {bits_str:>5} {e['flags']:<30} {fp_short}")
first_entry = False
else:
print(f"{'':<10} {'':>5} {'':>4} "
f"{alg_short:<20} {bits_str:>5} {e['flags']:<30} {fp_short}")
if duplicates:
print()
print(f'--- Duplicate Fingerprints: {len(duplicates)} ---')
for d in duplicates:
users_str = ', '.join(d['shared_by'])
print(f' {d["fingerprint"]} shared by: {users_str}')
print()
if exit_code == 0:
banner = '✓ All keys OK — no weak keys, no duplicates'
else:
reasons = []
if flagged_count > 0:
reasons.append(f'{flagged_count} flagged key(s)')
if len(duplicates) > 0:
reasons.append(f'{len(duplicates)} duplicate fingerprint(s)')
banner = f'⚠ Findings ({", ".join(reasons)}) — exit code {exit_code}'
print(f'{banner}')
print(f' Users: {len(results)} Total keys: {total_keys}')
sys.exit(exit_code)
if __name__ == '__main__':
main()
I set up nine synthetic accounts (RFC 5737 address ranges for from= restrictions). Alice gets Ed25519, Bob RSA-3072, Carol RSA-2048 + RSA-1024 legacy, Dave shares Bob’s key with a from= restriction, Erin has Alice’s key plus a commented-out line, and anon/nobody/nostatic syslog round out the test. All data is synthetic.

Running the audit against the synthetic data:
=== SSH Authorized Keys Audit Report ===
alice 1001 1 ed25519 256 OK SHA256:uhbAZ...
bob 1002 1 rsa 3072 OK SHA256:DO+qv...
carol 1003 2 rsa 2048 OK SHA256:3M+MZ...
rsa 1024 WEAK_1024bit SHA256:e7aCC...
dave 1004 2 rsa 3072 from=,restrict-agent SHA256:DO+qv...
ed25519 256 NOCOMMENT SHA256:uhbAZ...
erin 1005 1 ed25519 256 OK SHA256:uhbAZ...
nobody 1006 0 (no authorized_keys) [NO-AUTH]
anon 1007 1 ed25519 256 NOCOMMENT SHA256:sNlyh...
static 1008 0 (no authorized_keys) [NO-AUTH]
syslog 105 0 (no authorized_keys) [NO-AUTH]
--- Duplicate Fingerprints: 2 ---
SHA256:uhbAZm+0wCNiU2prBw1hLOLHv7bk+sN1ADvrgBh+VSM shared by: alice, dave, erin
SHA256:DO+qv7ZOJIJGGAlCCGIfzzUkQj9YNH5TXyjeuEO+sHA shared by: bob, dave
⚠ Findings (4 flagged key(s), 2 duplicate fingerprint(s)) — exit code 1
Users: 9 Total keys: 8The --json flag produces structured output for downstream tooling. Cron wrapper:
# In cron: audit every morning at 6 AM
6 6 * * * root /opt/ssh/ssh_keys_audit.py --json > /var/log/ssh-key-audit.json{
"total_users_scanned": 9,
"total_keys": 8,
"flagged_keys": 4,
...
"total_users_scanned": 9,
"total_keys": 8,
"flagged_keys": 4,
"duplicate_fingerprints": 2,
"duplicates": [
{"fingerprint": "SHA256:uhbAZm...+VSM","shared_by":["alice","dave","erin"]},
{"fingerprint": "SHA256:DO+qv...+sHA","shared_by":["bob","dave"]}
],
"exit_code": 1
}Each key gets one or more flags. Same approach I used for the SUID/world-writable file audit — classify, flag, exit 1 for cron:
| Flag | Meaning | Action |
|---|---|---|
OK | Meets strength, has comment, no dupe | None |
WEAK_{bits} | RSA < 2048 bits | Generate fresh Ed25519 or RSA-3072 |
NOCOMMENT | No identifying comment | ssh-keygen -c -C "user@host" |
from=/command= | Options prefix present | Review |
| Duplicate fp | Same key across accounts | Issue unique keys per user |

Continuation lines in authorized_keys are a trap. OpenSSH wraps long lines with a trailing backslash. If the parser doesn’t join them before tokenising, the second physical line becomes a PARSE_ERR. The script does .replace("\\n", "") capture_output=True early — tested against a real continuation artifact in the demo data.
I run this weekly. The cron caught a shared key I missed during a colo migration. Pair it with the sshd_config hardening audit and the IP-restricted SSH guide for a complete SSH hygiene stack. If you lock down PasswordAuthentication no but never audit the keys that are still authorised, you haven’t locked down anything.