Why the Idea Looks Attractive
System administrators often reach for cron to schedule repetitive tasks. Rotating SSH keys every few weeks seems like a neat way to keep access fresh, reduce the window for credential theft, and satisfy compliance checklists. The typical recipe reads like a short script that generates a new key pair, distributes the public key, and deletes the old private key—all triggered by a simple cron entry.
What Really Happens Under the Hood
The illusion of safety crumbles once we examine the hidden flow of data. A cron job runs as a specific user (often root or a service account). When the script writes a new private key to /tmp or another world‑writable directory, the file becomes visible to any local process that can read that location. Moreover, the cron environment is sparse: it inherits a limited PATH, no interactive shell, and no explicit error handling. If any step fails, the script may leave stale keys lying around, creating an unintended backdoor.
# Example of a naïve rotation script (DO NOT USE IN PRODUCTION)
#!/bin/bash
KEY_DIR="/tmp/ssh-rotate"
mkdir -p "$KEY_DIR"
ssh-keygen -t ed25519 -f "$KEY_DIR/id_ed25519" -N "" -q
cat "$KEY_DIR/id_ed25519.pub" >> /home/ubuntu/.ssh/authorized_keys
rm -f "$KEY_DIR/id_ed25519"
The snippet above illustrates three problems:
- Temporary storage exposure: The private key resides in
/tmpwhere any user can read it before it is deleted. - Lack of atomicity: The public key is appended without checking for duplicates, potentially bloating
authorized_keysand making revocation harder. - No verification step: If the
ssh-keygencall fails, the script still proceeds to modify the authorized keys file, possibly leaving a half‑updated state.
Consequences of Silent Failures
Cron does not send output to a console; unless you explicitly redirect stdout and stderr, failures are swallowed. Over weeks, a cascade of unnoticed errors can produce:
- Orphaned private keys on disk, searchable by attackers who have gained local access.
- Multiple identical public keys, making it impossible to tell which key corresponds to which rotation cycle.
- Accidental removal of a key that is still in use by a long‑running process, causing service outages.
# Redirect output to a log file for debugging (still not enough)
*/30 * * * * /usr/local/bin/rotate_ssh_keys.sh >> /var/log/ssh-rotate.log 2>&1
Even with logging, the core issue remains: the script runs with elevated privileges and manipulates authentication material without a verifiable audit trail. Attackers who compromise a low‑privilege account can read the log, infer the rotation schedule, and time a key‑theft attempt precisely when the new key is written but before the old one is purged.
Deconstructing a Safer Alternative
Instead of a blind cron job, adopt a two‑phase approach that separates key generation from distribution and uses a signed manifest to guarantee integrity. Below is a minimal prototype that demonstrates the concept.
# generate_key.sh – runs on a hardened bastion
#!/usr/bin/env python3
import os, json, subprocess, hashlib, base64
KEY_DIR = "/opt/ssh-rotate"
os.makedirs(KEY_DIR, exist_ok=True)
# 1️⃣ Generate key pair in memory
proc = subprocess.run(
["ssh-keygen", "-t", "ed25519", "-N", "", "-f", "-"],
capture_output=True, text=True
)
private_key = proc.stdout
public_key = subprocess.check_output(
["ssh-keygen", "-y", "-f", "-"], input=private_key.encode()
).decode()
# 2️⃣ Create a signed manifest
manifest = {
"public_key": public_key.strip(),
"timestamp": int(os.time()),
"fingerprint": hashlib.sha256(public_key.encode()).hexdigest()
}
manifest_json = json.dumps(manifest, separators=(",", ":"))
signature = subprocess.check_output(
["openssl", "dgst", "-sha256", "-sign", "/etc/ssh/rotate.key", "-out", "/dev/stdout"],
input=manifest_json.encode()
)
signed_blob = base64.b64encode(signature).decode()
# 3️⃣ Store artifacts securely
with open(f"{KEY_DIR}/manifest.json", "w") as f:
f.write(manifest_json)
with open(f"{KEY_DIR}/signature.b64", "w") as f:
f.write(signed_blob)
with open(f"{KEY_DIR}/private.key", "w", opener=lambda p, f: os.open(p, f, 0o600)) as f:
f.write(private_key)
The script never writes the private key to a world‑writable location. It stores the key with 0600 permissions, generates a JSON manifest, and signs it with a dedicated HSM‑backed key. Distribution is handled by a separate, audited process that validates the signature before appending the new public key.
# distribute_key.sh – runs on each target host (invoked via Ansible)
#!/bin/bash
MANIFEST="/opt/ssh-rotate/manifest.json"
SIGNATURE="/opt/ssh-rotate/signature.b64"
PUBLIC_KEY=$(jq -r '.public_key' "$MANIFEST")
SIG=$(base64 -d "$SIGNATURE")
# Verify signature (simplified)
if openssl dgst -sha256 -verify /etc/ssh/rotate.pub -signature <(echo "$SIG") "$MANIFEST" >/dev/null; then
echo "$PUBLIC_KEY" >> /home/ubuntu/.ssh/authorized_keys
else
echo "Signature verification failed!" >> /var/log/ssh-rotate-error.log
exit 1
fi
By splitting responsibilities, you gain:
- Cryptographic proof that the public key originated from a trusted generator.
- Atomic updates – the target host only writes the key after successful verification.
- Auditable logs that record both the manifest and verification result.
Security and Best Practices
If you still need to schedule rotation, follow these guidelines:
- Never store private keys in temporary directories. Use a dedicated, encrypted volume with strict ACLs.
- Validate every step. Exit the script on any non‑zero return code and roll back partially applied changes.
- Prefer a configuration management tool. Ansible, Chef, or Puppet can enforce key distribution with idempotent playbooks, eliminating the need for ad‑hoc cron entries.
- Maintain a revocation list. Keep a separate file of keys that have been retired; do not rely on manual removal from
authorized_keys. - Rotate the signing key regularly. The trust chain is only as strong as the root key used to sign manifests.
“Automation without verification is a shortcut to disaster; every automated credential change must be accompanied by cryptographic proof.” — Senior Security Engineer, 2026
Conclusion
Cron‑driven SSH key rotation promises simplicity but delivers hidden exposure. The root cause is the lack of atomicity, insufficient permission hardening, and the absence of a verifiable handoff between generation and deployment. By refactoring the workflow into distinct, signed phases and leveraging proven configuration tools, you retain the operational benefits of rotation while eliminating the stealthy attack surface that cron scripts create.
The takeaway is clear: automate responsibly. Treat every credential as a high‑value asset, protect it with defense‑in‑depth, and never let a single line in crontab become the weakest link in your security chain.