如何通过反向DNS查询匹配authorized_keys主机名并实现SSH密钥轮换?
Alright, let's build out this SSH key rotation system that enforces your rule of keeping only the latest key per admin laptop on each server, using reverse DNS matching to tie keys to specific machines. Here's a step-by-step implementation:
1. Server-side:
update_keys.sh Script This script runs on each server, handles reverse DNS lookup to identify the admin laptop, cleans up old keys for that laptop, and adds the new one. It's designed to be executed via SSH from an admin machine.
#!/bin/bash # Configure path to authorized_keys (adjust based on your setup) AUTH_KEYS="/home/$USER/.ssh/authorized_keys" # Create timestamped backup to avoid data loss BACKUP_FILE="$AUTH_KEYS.bak.$(date +%Y%m%d%H%M%S)" # Ensure script is run via SSH (we need client IP for reverse DNS) if [ -z "$SSH_CLIENT" ]; then echo "Error: This script must be executed over SSH from an admin laptop." exit 1 fi # Extract client IP from SSH connection metadata CLIENT_IP=$(echo "$SSH_CLIENT" | awk '{print $1}') # Perform reverse DNS lookup to get the admin laptop's hostname CLIENT_HOSTNAME=$(dig -x "$CLIENT_IP" +short | sed 's/\.$//') if [ -z "$CLIENT_HOSTNAME" ]; then echo "Error: Failed to resolve reverse DNS for IP $CLIENT_IP. Check DNS records." exit 1 fi # Backup current authorized_keys before making changes cp "$AUTH_KEYS" "$BACKUP_FILE" echo "Backed up authorized_keys to $BACKUP_FILE" # Delete all existing keys tied to this admin laptop (matches hostname in key comments) sed -i.bak "/$CLIENT_HOSTNAME/d" "$AUTH_KEYS" # Read the new public key from standard input NEW_KEY=$(cat) if [ -z "$NEW_KEY" ]; then echo "Error: No public key provided. Did you pipe the key to this script?" exit 1 fi # Add a descriptive comment to the new key (includes hostname and timestamp for traceability) KEY_COMMENT="admin-laptop:$CLIENT_HOSTNAME:$(date +%Y%m%d%H%M%S)" # Reconstruct the key with the standardized comment PUB_KEY_CORE=$(echo "$NEW_KEY" | awk '{print $1, $2}') FINAL_KEY="$PUB_KEY_CORE $KEY_COMMENT" # Append the new key to authorized_keys echo "$FINAL_KEY" >> "$AUTH_KEYS" echo "Success! Updated keys for admin laptop $CLIENT_HOSTNAME. All old keys removed, new key added."
2. Admin Laptop-side:
rotate_keys.sh Script This script runs on any admin laptop, generates a new SSH key pair, and pushes it to all servers by executing the server-side update_keys.sh.
#!/bin/bash # Directory to store rotated keys (keeps old keys for rollback if needed) ROTATED_KEYS_DIR="$HOME/.ssh/rotated_keys" mkdir -p "$ROTATED_KEYS_DIR" # Generate a new ed25519 key pair (more secure than RSA) with a timestamped name NEW_KEY_BASE="$ROTATED_KEYS_DIR/id_rsa_$(date +%Y%m%d%H%M%S)" ssh-keygen -t ed25519 -f "$NEW_KEY_BASE" -N "" -C "rotation:$(hostname):$(date +%Y%m%d%H%M%S)" # Read the new public key content NEW_PUB_KEY=$(cat "$NEW_KEY_BASE.pub") # List of servers to update (replace with your actual server list, or load from a config file) SERVERS=("server-01.example.com" "server-02.example.com" "server-03.example.com") # Iterate over each server and push the new key for SERVER in "${SERVERS[@]}"; do echo "Updating keys on $SERVER..." # Pipe the new public key to the server's update_keys.sh (use sudo if needed for file permissions) echo "$NEW_PUB_KEY" | ssh "$SERVER" "sudo /usr/local/bin/update_keys.sh" if [ $? -eq 0 ]; then echo "✅ Successfully updated keys on $SERVER" else echo "❌ Failed to update keys on $SERVER. Check SSH access or script permissions." fi done # Optional: Update local SSH config to use the new key for server connections echo -e "\nHost ${SERVERS[*]}" >> "$HOME/.ssh/config" echo " IdentityFile $NEW_KEY_BASE" >> "$HOME/.ssh/config" echo "Updated local SSH config to use the new key for server connections."
3. Key Setup & Validation Steps
- Reverse DNS Configuration: Ensure every admin laptop has a stable reverse DNS record (e.g.,
admin-laptop-john.example.com). This is critical for the server to correctly identify which keys belong to which laptop. - Permissions: On servers, make sure
update_keys.shis executable (chmod +x /usr/local/bin/update_keys.sh) and that the user executing it (via SSH) has permission to modify theauthorized_keysfile (use sudo if targeting system users like root). - Verify Compliance: After running a rotation, check any server's
authorized_keysfile—you should only see one entry per admin laptop hostname, and it should be the latest timestamped key.
How This Enforces Your Rules
- One Key Per Admin Laptop: Every time
update_keys.shruns, it deletes all existing keys tied to the admin laptop's hostname before adding the new one. This guarantees only the latest key is retained. - Reverse DNS Matching: The script uses the admin laptop's IP (from the SSH connection) to resolve its hostname, ensuring keys are tied to the actual machine rather than a static username or comment that could be spoofed.
内容的提问来源于stack exchange,提问作者Jabari Dash
相关产品推荐
相关产品推荐

