Blog | G5 Cyber Security

SSH: Private Key Exposure – What to do

TL;DR

You accidentally used your private SSH key with the ssh -i command. This is bad! Revoke the compromised key from authorized keys on all servers, and generate a new key pair. Follow these steps to minimise damage.

Steps to Recover

  1. Identify Affected Servers: Think about which servers you’ve used this private key with recently. Check your ~/.ssh/config file for entries that might automatically use the compromised key. Look for lines like:
    Host server_alias
      IdentityFile /path/to/your/private_key
  2. Revoke the Key: For each affected server, remove the public key corresponding to your compromised private key from the ~/.ssh/authorized_keys file on that server. You’ll need SSH access (using a different key!) or console access.
    • Log in to the server using a working SSH key.
    • Open the ~/.ssh/authorized_keys file with a text editor (e.g., nano ~/.ssh/authorized_keys).
    • Find the line containing your compromised public key. It will start with something like ssh-rsa, ssh-ed25519 or similar.
    • Delete that entire line.
    • Save and close the file.
  3. Generate a New Key Pair: Create a new SSH key pair.
    ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -C "your_email@example.com"

    Replace your_email@example.com with your email address. Consider using a stronger key type like ed25519: ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519 -C "your_email@example.com"

    When prompted, set a strong passphrase for your new key.

  4. Add the New Public Key: Add the new public key to the ~/.ssh/authorized_keys file on each affected server.
    • Copy the contents of ~/.ssh/id_rsa.pub (or ~/.ssh/id_ed25519.pub)
    • Log in to the server using a working SSH key.
    • Open the ~/.ssh/authorized_keys file with a text editor.
    • Paste your new public key on a new line at the end of the file.
    • Save and close the file.
  5. Test the New Key: Try connecting to each server using the new key.
    ssh -i ~/.ssh/id_rsa user@server_alias

    Or, if you used ed25519:

    ssh -i ~/.ssh/id_ed25519 user@server_alias
  6. Check SSH Logs: Review the SSH logs on affected servers for any suspicious activity around the time of the compromise. Look for failed login attempts or unusual commands being executed.

    Log locations vary by system, but common places include /var/log/auth.log and /var/log/secure.

  7. Consider Key-Based Authentication Only: Disable password authentication on your servers to further improve cyber security. This forces users to use SSH keys.
    sudo nano /etc/ssh/sshd_config

    Find the line PasswordAuthentication yes and change it to PasswordAuthentication no. Restart the SSH service: sudo systemctl restart sshd.

Exit mobile version