Table of Contents

Ubuntu - SSH - Manage SSH Key File With Passphrase

For enhanced security, SSH should only be accessed by key file and not with a password.

However, what if your key is lost or stolen by hackers? Time to protect your sensitive SSH key with a passphrase.

When storing a private key on a server, I’d opt for a hardware option (HSM) since it’s likely the key will need to be actively used and thus a passphrase can’t be securely used (think automated use of a server-side private key).


Cheat Sheet

NameSummary
Load key filessh-add ~/.ssh/id_rsa
Remove all loaded keysssh-add -D
Whether it’s encryptedgrep “ENCRYPTED” id_rsa
Add/Change passphrasessh-keygen -p -f id_dsa
Remove passphrasessh-keygen -p -P $passwd -N “” -f id_rsa
Load key without promptCheck link: here

Add passphrase to existing ssh key

We can easily use ssh-keygen to add a passphrase. This certainly gives us extra security benefit. Next, what’s the impact of this change?

# Change file mode to allow overwrite
chmod 700 id_rsa
 
# Add passphrase to key file
ssh-keygen -p -f id_rsa
 
# Denny-mac:.ssh mac$ ssh-keygen -p -f id_rsa
# Key has comment 'id_rsa'
# Enter new passphrase (empty for no passp...
# Enter same passphrase again: 
# Your identification has been saved with ...

Load protected ssh key without prompt

Pity that ssh-add itself doesn’t have native support for this. Here is a workaround. A bit tricky, I admit.

# Specify your passphrase here
export YOUR_PASSPHRASE="XXX"
 
# Load protected key without prompt
echo "echo $YOUR_PASSPHRASE" > /tmp/mypass
chmod 700 /tmp/mypass
cat id_rsa| SSH_ASKPASS=/tmp/mypass ssh-add -
 
# Verify loaded certificate
ssh-add -l

Change passphrase for existing private key

Run below command. You will be asked to input old passphrase and new one. If the key is not encrypted, just press enter in the terminal.

ssh-keygen -p -f ~/.ssh/id_dsa

Remove passphrase

Use openssl to remove passphrase. You will need to manually input old passphrase.

openssl rsa -in id_rsa -out id_rsa_new

Same can be done by ssh-keygen. The amazing part is no required human intervene. Totally automated.

ssh-keygen -p -P "$OLDPASS" -N "" -f id_rsa

More Reading: Reverse SSH Tunnel: Export Your Mac Laptop To The Internet.

Footnotes:

[1] unix.stackexchange.com/questions/90853/how-can-i-run-ssh-add-automatically-without-password-prompt [2] www.thinkplexx.com/learn/howto/security/ssl/remove-passphrase-password-from-private-rsa-key [3] stackoverflow.com/questions/112396/how-do-i-remove-the-passphrase-for-the-ssh-key-without-having-to-create-a-new-ke