Any serious DevOps will only SSH by the key file, not with a password. Right? And mostly, our powerful key file can unlock many critical ENVs. Have you ever uploaded your private key to other ENVs, like Jumpbox? What if your key is magically stolen by hackers somehow?
Time to protect your sensitive SSH key with a passphrase, and live with it, headache-free.
|Load key file||ssh-add ~/.ssh/id_rsa|
|Remove all loaded keys||ssh-add -D|
|Whether it’s encrypted||grep “ENCRYPTED” id_rsa|
|Add/Change passphrase||ssh-keygen -p -f id_dsa|
|Remove passphrase||ssh-keygen -p -P $passwd -N “” -f id_rsa|
|Load key without prompt||Check 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. What’s the impact of this change?
- You never use your private key other than your computer, right? If yes, there's nothing you need to worry about. One tiny difference: you might be asked to input the passphrase once. Check all loaded keys by ssh-add -l.
- In some cases, we might use key files to do a passwordless login with remote servers. For example, the SSH tunnel for port forwarding, the SSH from Jumpbox to other machines, etc. Then, we have to make sure that the key file is correctly loaded and recognized. Run ssh-add ./id_rsa, then input passphrase manually. This also can be done automatically, which I will explain it shortly.
# 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
It's a 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 the below command. You will be asked to input the old passphrase and a new one. If the key is not encrypted, just press enter in the terminal.
ssh-keygen -p -f ~/.ssh/id_dsa
Use openssl to remove the passphrase. You will need to manually input the old passphrase.
openssl rsa -in id_rsa -out id_rsa_new
The same can be done by ssh-keygen. The amazing part is that there is no required human intervention; it's totally automated.
ssh-keygen -p -P "$OLDPASS" -N "" -f id_rsa