Best Practices for Key Security
Best Practices for Key Security
Maintaining SSH key security requires ongoing vigilance and proper operational procedures. Keys provide powerful access capabilities, making their protection paramount to overall system security.
Implement key protection measures:
# Set correct permissions on SSH directory and files
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_*
chmod 644 ~/.ssh/id_*.pub
chmod 644 ~/.ssh/config
chmod 600 ~/.ssh/authorized_keys
# Create backup of private keys (encrypted)
tar -czf - ~/.ssh/id_* | \
openssl enc -aes-256-cbc -salt -out ssh-keys-backup.tar.gz.enc
# Verify key fingerprints
ssh-keygen -lf ~/.ssh/id_ed25519.pub
# SHA256:AbCd... 255 [email protected] (ED25519)
Regular key rotation maintains security over time:
#!/bin/bash
# rotate_ssh_keys.sh - Automated key rotation
OLD_KEY="$HOME/.ssh/id_ed25519"
NEW_KEY="$HOME/.ssh/id_ed25519_new"
BACKUP_DIR="$HOME/.ssh/old_keys/$(date +%Y%m%d)"
# Generate new key
ssh-keygen -t ed25519 -f "$NEW_KEY" -C "[email protected]$(date +%Y%m%d)"
# Create backup directory
mkdir -p "$BACKUP_DIR"
# Deploy new public key alongside old key
for server in $(grep "Host " ~/.ssh/config | grep -v "*" | awk '{print $2}'); do
echo "Deploying new key to $server"
ssh-copy-id -i "${NEW_KEY}.pub" "$server"
done
# Test new key
echo "Testing new key access..."
ssh -i "$NEW_KEY" [email protected] exit && echo "Success" || exit 1
# Backup and replace old key
mv "$OLD_KEY" "$BACKUP_DIR/"
mv "${OLD_KEY}.pub" "$BACKUP_DIR/"
mv "$NEW_KEY" "$OLD_KEY"
mv "${NEW_KEY}.pub" "${OLD_KEY}.pub"
echo "Key rotation complete. Old keys backed up to $BACKUP_DIR"