Build a Python SSH Key Auditor: Find Weak Keys Before Attackers Do
SSH keys are the front door to your servers — and most teams have no idea how many keys exist, how old they are, or whether they are weak. Today we will build a Python auditor that scans a system for SSH keys, checks their type and strength, and flags the risky ones.
The Code
import osimport subprocessfrom pathlib import Path# Minimum safe key sizes (bits)MIN_BITS = {"rsa": 3072, "ecdsa": 256, "ed25519": 256, "dsa": 0}def audit_key(pubkey_path): """Check one public key file and return a list of issues.""" issues = [] try: result = subprocess.run( ["ssh-keygen", "-lf", str(pubkey_path)], capture_output=True, text=True, check=True ) parts = result.stdout.split() bits, keytype = int(parts[0]), parts[3].strip("()").lower() except Exception: return [f"Could not read {pubkey_path}"] if keytype == "dsa": issues.append(f"{pubkey_path}: DSA is broken — replace immediately") elif keytype == "rsa" and bits < MIN_BITS["rsa"]: issues.append(f"{pubkey_path}: RSA {bits} bits is too weak (use 3072+)") elif keytype == "ecdsa" and "nist256" not in str(bits): issues.append(f"{pubkey_path}: ECDSA below 256 bits — upgrade") if keytype not in MIN_BITS: issues.append(f"{pubkey_path}: Unknown key type {keytype}") return issuesdef audit_authorized_keys(home): """Check authorized_keys files for risky entries.""" issues = [] auth = Path(home) / ".ssh" / "authorized_keys" if not auth.exists(): return issues for line in auth.read_text().splitlines(): line = line.strip() if not line or line.startswith("#"): continue fields = line.split() if len(fields) < 2: issues.append(f"{auth}: malformed line — {line[:40]}") continue keytype = fields[0] if keytype in ("ssh-dss",): issues.append(f"{auth}: DSA key still authorized — remove it") return issuesdef main(): all_issues = [] for home in [str(Path.home()), "/root", "/home"]: base = Path(home) if not base.exists(): continue ssh_dir = base / ".ssh" if ssh_dir.exists(): for pub in ssh_dir.glob("*.pub"): all_issues += audit_key(pub) all_issues += audit_authorized_keys(str(base)) # Also check system-wide host keys for pub in Path("/etc/ssh").glob("ssh_host_*.pub"): all_issues += audit_key(pub) if not all_issues: print("No SSH key issues found. Nice work.") else: print(f"Found {len(all_issues)} issue(s):") for issue in all_issues: print(f" - {issue}")if __name__ == "__main__": main()
How It Works
- Key strength check — runs ssh-keygen -lf on every public key it finds and compares the bit size against modern minimums: RSA 3072+, ECDSA 256, Ed25519.
- Dead algorithm detection — flags DSA keys, which are cryptographically broken and should never be used.
- Authorized keys audit — reads every authorized_keys file and flags malformed lines and lingering DSA entries.
- Host key coverage — also checks the server’s own host keys under /etc/ssh, which are easy to forget.
Try It
Save as ssh_audit.py and run python3 ssh_audit.py on your own machine or server. A clean result is great news. A list of weak keys is a to-do list — replace each one with a fresh Ed25519 key:
ssh-keygen -t ed25519 -C "your-machine-2026"
Level Up
- Add a passphrase check: private keys without a passphrase are unprotected if the file leaks.
- Scan for keys shared across servers — the same public key on ten machines means one compromise opens ten doors.
- Turn it into a scheduled job with cron so new weak keys get caught the week they appear, not years later.
SSH keys are credentials, and credentials rot silently. Audit them before an attacker audits them for you.
Only test systems you own or have written permission to test.



Comments
Post a Comment