Settings up keys for SSH access

Setting up is very easy and secure and can give a server simple MFA for access.

Setting up is very easy and secure.  If you are automating access in other applications such as Visual Studio Code, this step saves time from repeatedly typing in a password.

I also maintain multiple keys for access.  One for sudo use where the key is encrypted for basic MFA.  One for development using Visual Studio Code.

Generating Keys with ssh-keygen

This is the easy task.

Type in "ssh-keygen" into the command prompt in any location.  The default location will be prompted.  From this prompt, type in the name of the key file.

$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/.ssh/id_rsa):

You will receive an other prompt for a password to encrypt the key.  This step will add a second factor for authentication.  If someone gains access to your key, they still need to know the password to decrypt the key.  Something you know (password) and something you have (key) are required for access.  I recommend using the encryption password if the key is used for a sudo or root account.

Let's assume you gave the name "server" to the key pair.  Two files will be generated in the location – "server" and "server.pub"

"server" is your private key.  "server.pub" is your public key and will be published to the server for remote access.

Publishing Keys with ssh-copy-id

This step tripped my up initially as some tutorials leave out the "-i" flag.  The flag tells the command which key to publish to the server for access.

$ ssh-copy-id -i server.pub user@x.x.x.x
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "server.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
user@x.x.x.x's password: 

Number of key(s) added: 1

After publishing the key, you can now login with the following command without a password.

$ ssh -i server user@x.x.x.x

Or  you can go on to the next step and even omit "-i server" from the command!

Setting up ssh configuration

This next step is useful for integrating Visual Studio Code with ssh connections for editing projects on another server.  

Copy the private key to the user account on the system with Visual Studio Code installed.  I copy the file to the ".ssh" folder under the user as this location is also where the ssh config file is located.  An example of this folder location would be "/home/.ssh".

Open the config file in this same folder with you favorite editor.  Add the following information to the file.

Host server
    HostName x.x.x.x
    User user
    IdentityFile ./server

Replace the name "server" with the hostname of your choice.

You can find me on Mastodon at @mojoology@mastodon.social.