Skip to main content

SSH

Developer with a lock and a key
SSH Keys

SSH keys are a pair of cryptographic keys that can be used to establish a secure and encrypted connection between a client and a server over the SSH (Secure Shell) protocol. They are an alternative to using passwords for authentication and are considered more secure and convenient for automated processes like scripts and continuous integration/deployment workflows.

Intro​

Types of SSH Keys​

There are primarily two types of SSH keys:

  1. Private Key: This is kept secret and secure by the user. It should never be shared or transmitted. The private key is used to decrypt data sent from the server or to authenticate against the server.
  2. Public Key: This can be freely shared and is placed on the server you wish to connect to. The public key is used to encrypt messages that only the corresponding private key can decrypt.

How SSH Keys Work​

  • Generation: The first step is to generate a pair of keys using a tool like ssh-keygen on Linux or macOS, or third-party tools on Windows.
  • Deployment: The public key is then placed in a special file (~/.ssh/authorized_keys) on the server you wish to access.
  • Authentication: When you attempt to connect to the server, the server challenges the client to prove possession of the private key. The client signs a message with its private key, and the server uses the public key to verify the signature. If the verification is successful, the connection is established without needing to input a password.

Benefits of SSH Keys​

  • Security: SSH keys are nearly impossible to brute force, making them significantly more secure than password-based authentication.
  • Convenience: They allow for passwordless sign-ins, which can streamline workflows, especially for automated processes.
  • Control: Keys can be generated with or without passphrases. Adding a passphrase provides an extra layer of security, requiring the user to enter the passphrase the first time the key is used in a session.

Best Practices​

  • Protect your private key: Keep it secure and ensure it's not accessible to others.
  • Use strong passphrases: When generating SSH keys, you can use a passphrase for an added layer of security.
  • Rotate keys regularly: Regularly update and change SSH keys to mitigate the risks of key compromise.
  • Limit access: Only copy your public key to servers and accounts where necessary.

SSH keys are widely used in various applications beyond secure shell access, including secure file transfer (SFTP), secure copy (SCP), and more, making them a fundamental aspect of modern security practices in network communication and remote server management.


Generating an SSH key pair​

Generating an SSH key pair is a straightforward process that involves using the ssh-keygen command on Linux, macOS, and Windows (if you have the Windows Subsystem for Linux or Git Bash installed). Here's how you can do it:

Step 1: Open a Terminal​

  • Linux/macOS: Open your terminal application.
  • Windows: Open Git Bash or WSL if you have them installed.

Step 2: Generate SSH Key Pair​

Type the following command and hit Enter. You can replace your_email@example.com with your email address as a way to label your SSH key:

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
  • -t rsa: Specifies the type of key to create, in this case RSA. RSA is widely used, but you can also use other types like ECDSA or Ed25519.
  • -b 4096: Specifies the key length. 4096 bits is recommended for sufficient security.
  • -C "your_email@example.com": Adds a label to the key with your email address for identification.

Step 3: Specify Where to Save the Key​

After executing the command, you'll be asked to enter a file in which to save the key. Press Enter to accept the default location (usually ~/.ssh/id_rsa):

Enter a file in which to save the key (/your/home/directory/.ssh/id_rsa): [Press enter]

Step 4: Enter a Passphrase (Optional)​

Next, you'll be prompted to enter a passphrase. This is an optional but recommended step for added security. If someone were to obtain your private key, they would also need the passphrase to use it. You can press Enter without typing anything to skip this step:

Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]

Step 5: Public and Private Keys​

After completing these steps, two files will be generated:

  • The private key, saved to ~/.ssh/id_rsa
  • The public key, saved to ~/.ssh/id_rsa.pub

Step 6: Copy the Public Key to Your Server​

To use the SSH key, you'll need to copy the public key to your server. You can do this manually or use ssh-copy-id if it's available on your system:

ssh-copy-id user@hostname

Replace user@hostname with your username and the hostname or IP address of the server you're connecting to. This command will add your public key to the ~/.ssh/authorized_keys file on the server, allowing you to log in and execute commands based on the public key authentication.

Note for Windows Users​

If you're using Windows without WSL or Git Bash, you can generate SSH keys with PuTTYgen, a graphical tool that comes with PuTTY. The process involves opening PuTTYgen, generating the keys, and saving the private and public keys to files.

And that's it! You now have an SSH key pair that you can use for secure, passwordless authentication to servers that support it.


Adding several SSH keys​

Adding several SSH keys for use with different servers or for different purposes (like personal and work accounts) follows a process similar to generating and adding a single key, but with attention to managing multiple keys efficiently. Here's how to do it:

1. Generate Multiple SSH Keys​

Follow the steps to generate an SSH key pair for each purpose or account, as described previously. When generating each key, make sure to save each one with a unique name to avoid overwriting:

ssh-keygen -t rsa -b 4096 -C "personal_email@example.com" -f ~/.ssh/id_rsa_personal
ssh-keygen -t rsa -b 4096 -C "work_email@example.com" -f ~/.ssh/id_rsa_work

In these commands, -f specifies the filename for the key. Replace personal_email@example.com and work_email@example.com with your actual email addresses.

2. Add SSH Keys to the SSH Agent​

To manage multiple SSH keys, you can add them to the SSH agent. This step is optional but recommended for convenience. First, start the SSH agent in the background:

eval "$(ssh-agent -s)"

Then, add each SSH key to the SSH agent using ssh-add:

ssh-add ~/.ssh/id_rsa_personal
ssh-add ~/.ssh/id_rsa_work

You might need to enter the passphrase for each key if you set one during key generation.

ssh-add -K ~/.ssh/your_private_key

Add your SSH private key to the ssh-agent using ssh-add -K ~/.ssh/your_private_key, where your_private_key is the path to your private key. The -K option adds the passphrase of your private key to the macOS Keychain, so you don't have to enter it every time.

3. Configure SSH to Use Specific Keys for Different Hosts​

You can create an SSH config file to specify which key should be used for each server. Edit (or create if it doesn't exist) the ~/.ssh/config file:

nano ~/.ssh/config

Add configurations for each host, specifying the Host, HostName, User, and IdentityFile (the path to your private key) for each connection:

# Personal server
Host personal
HostName personal.example.com
User myusername
IdentityFile ~/.ssh/id_rsa_personal

# Work server
Host work
HostName work.example.com
User myusername
IdentityFile ~/.ssh/id_rsa_work

Replace personal.example.com and work.example.com with the actual hostnames or IP addresses of your servers. myusername should be replaced with your username on those servers.

4. Connecting to Your Servers​

Now, when you want to connect to one of your servers, you can use the Host label from your config file:

ssh personal

or

ssh work

SSH will automatically use the correct private key for each server based on the configuration.

5. Copy the Public Keys to Your Servers​

For each public key, you'll need to add it to the ~/.ssh/authorized_keys file on the corresponding server. You can do this manually or use tools like ssh-copy-id, specifying the path to the correct public key:

ssh-copy-id -i ~/.ssh/id_rsa_personal.pub user@personal.example.com
ssh-copy-id -i ~/.ssh/id_rsa_work.pub user@work.example.com

By following these steps, you can efficiently manage and use multiple SSH keys for different purposes or accounts, enhancing your workflow and security.


How can I know which keys I already have?​

To find out which SSH keys you already have, you can look in your SSH directory, typically located at ~/.ssh/ on your machine. SSH keys are usually stored in this directory, with the private keys and their corresponding public keys sharing the same filename but with different extensions. Private keys usually have no extension (e.g., id_rsa, id_ecdsa, id_ed25519), and public keys have a .pub extension (e.g., id_rsa.pub, id_ecdsa.pub, id_ed25519.pub).

Here's how to list your existing SSH keys:

On Linux and macOS​

  1. Open a Terminal: Start by opening your terminal application.

  2. List SSH Keys: Use the ls command to list the contents of your SSH directory:

    ls -l ~/.ssh

    This command will show you all the files in your ~/.ssh directory. You're looking for pairs of files for each key: one with the extension .pub (the public key) and one without (the private key).

On Windows​

If you're using Windows, you might have SSH keys stored in different locations based on the software you're using (e.g., PuTTY, WinSCP, or if you're using the Windows Subsystem for Linux (WSL)).

  • For WSL: Open your WSL terminal and use the same ls command as above.
  • For Git Bash: Open Git Bash and use the same command to list the SSH keys.
  • For PuTTY: Keys are not stored in a directory but rather as files where you've saved them. You might have used PuTTYgen to generate keys, so you'll need to remember where you saved these files.

Viewing Key Fingerprints​

To further identify your keys, you can display their fingerprints by using the ssh-keygen command. This can be useful for matching keys on your client with those uploaded to servers or services like GitHub:

ssh-keygen -l -f ~/.ssh/id_rsa.pub

Replace id_rsa.pub with the filename of your public key. This command will show you the fingerprint of your public key, which uniquely identifies the key.

No Keys Found?​

If you don't find any keys or the ~/.ssh directory does not exist, it likely means you haven't generated SSH keys on that machine yet. In that case, you can generate a new SSH key pair by following the instructions provided in earlier messages about generating SSH keys.

Knowing which SSH keys you already have can help you manage your keys better, ensuring you use the appropriate keys for different servers or services without generating unnecessary duplicates.


In the context of SCM (Source Code Management)​

SSH keys play a crucial role in securely managing access to Git repositories hosted on platforms like GitHub and GitLab. Using SSH keys, developers can securely push and pull changes to repositories without needing to enter their username and password each time. This method is not only more secure than password-based authentication but also more convenient for continuous integration/continuous deployment (CI/CD) workflows and for developers working on multiple projects.

How SSH Keys Work with GitHub and GitLab​

When you use SSH keys with GitHub or GitLab, you're establishing a secure channel between your computer and the Git server. Here's the general workflow:

  1. Generate SSH Key Pair: First, you generate an SSH key pair on your local machine. This gives you a private key (which you keep secure and never share) and a public key.

  2. Add Public Key to GitHub or GitLab: You then add your public key to your GitHub or GitLab account. This lets the platform recognize and authenticate your computer without needing your account password.

  3. Clone, Pull, Push Over SSH: Once your SSH key is added to your account, you can clone repositories using SSH URLs, and securely push or pull changes. The SSH protocol encrypts your connection, ensuring your data remains secure in transit.

Setting Up SSH Keys for GitHub and GitLab​

GitHub:

  1. Generate an SSH Key: Use the ssh-keygen command to generate a new SSH key pair.

    ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

    Follow the prompts to complete the key generation, optionally adding a passphrase for extra security.

  2. Add the SSH Key to Your GitHub Account:

    • Copy your public key to the clipboard. On Linux and macOS, you can use pbcopy < ~/.ssh/id_rsa.pub. On Windows, you can display the key with cat ~/.ssh/id_rsa.pub and copy it manually.
    • Go to GitHub, navigate to "Settings" > "SSH and GPG keys" > "New SSH key", paste your public key into the field, and save it.

GitLab:

  1. Generate an SSH Key: If you haven't already, generate your SSH key pair.

  2. Add the SSH Key to Your GitLab Account:

    • Copy your public key to the clipboard.
    • In GitLab, go to your profile settings, find "SSH Keys", paste your public key into the provided text area, and add it.

Best Practices​

  • Use a Strong Passphrase: Adding a passphrase to your SSH key adds an extra layer of security.
  • Keep Your Private Key Secure: Never share your private key. If it's compromised, revoke it immediately from your GitHub or GitLab account.
  • Use Different Keys for Different Platforms: For added security, consider using separate SSH key pairs for different services or roles.
  • Regularly Review and Update Keys: Periodically check the SSH keys associated with your GitHub and GitLab accounts. Remove any that are no longer in use or are from unknown sources.

Benefits for Developers​

Using SSH keys with GitHub and GitLab simplifies many tasks for developers:

  • Secure Operations: Your operations are encrypted, making it safe to push and pull data even over insecure networks.
  • Streamlined Workflow: No need to enter your username and password for every Git operation.
  • Automation Friendly: SSH keys are ideal for scripts, automated builds, and deployments that interact with GitHub or GitLab repositories.

In summary, SSH keys are an essential tool for secure and efficient workflow management on GitHub and GitLab, offering both security and convenience for developers and teams.