# How SSH Key Authentication Works

I recently started following [this course](https://learntocloud.guide) to learn about cloud engineering. Phase 1 focused on Linux and Bash and involved taking part in a lab. During the lab, I had to use a virtual machine (VM) hosted on an AWS EC2 instance, and one of the challenges involved SSH-ing into a user's account on the machine.

I wasn't new to SSH or its uses, but the lab got me thinking about how it works and why it's used. I went to read about eventually decided to write about what I learnt.

**What I talk about**

- How SSH keys work (in plain language)
- How to generate a key pair and which algorithm to pick
- How to install your public key for another user on the same machine
- How to connect with that key, and what a `.pem` file is

---

## Table of Contents

- [The Core Idea](#the-core-idea)
- [1. Generating a Key Pair](#1-generating-a-key-pair)
- [2. SSH Key Algorithms](#2-ssh-key-algorithms)
- [3. Setting the Public Key on the Server](#3-setting-the-public-key-on-the-server)
- [4. Connecting to the vault User](#4-connecting-to-the-vault-user)
- [5. How to Get Your Private Key for a Remote Server?](#5-how-to-get-your-private-key-for-a-remote-server)
- [Things I Learnt Along the Way](#things-i-learnt-along-the-way)
- [References](#references)

---

## The Core Idea

Imagine you and a friend move to different cities but still want to exchange journals every month. You could simply send them through the post, but how would you prevent someone else from reading them before they reach your friend?
So, you decide to lock each journal before sending it and agree on a secret language that only the two of you understand.

To make this work, you each have two matching keys: a private key that you keep to yourself and a public key that you share. These keys help you verify each other's identity and establish a secure way to communicate, ensuring that only you and your friend can understand what's being shared.

Now, let's relate this to SSH.

When you connect to a server, it needs to verify that you own the private key corresponding to the public key it has stored for you. It does this by sending a cryptographic challenge, which your SSH client signs using your private key. The server then uses your public key to verify the signature. If it checks out, you're authenticated without your private key ever leaving your computer.

But what happens after authentication?

Rather than using your public and private keys to encrypt every command, keystroke, or file transfer, SSH establishes a temporary **session key** during the handshake.

Both your computer and the server participate in a key exchange mechanism, such as Diffie-Hellman (DH) or Elliptic-Curve Diffie-Hellman (ECDH), to independently derive the same shared secret without transmitting it over the network. This secret is then used to derive the encryption keys that secure all communication between them.

These session keys protect your commands, keystrokes, and file transfers from anyone trying to intercept the connection. They're specific to that session, and fresh keys are established whenever a new SSH connection is made.

## 1. Generating a Key Pair

I did this as a user on the VM, and I had created another user on the same VM that I would connect to using SSH.

> I did all of this on one VM, but you can also have a separate remote server and bring the private key to your local computer. Some cloud providers (like AWS) do this for you, but then the private key must be transferred to you, which adds risk. I'll talk more about this later.

```bash
ssh-keygen -t ed25519 -C "you@example.com"
```

| Flag | Meaning |
|---|---|
| `-t` | The algorithm (key type) |
| `-C` | A comment, just a label so you can recognise the key later |

You'll be asked two things:

1. **Where to save it.** The default (`~/.ssh/id_ed25519`) is fine.
2. **A passphrase.** Set one. It encrypts the private key on disk, so a stolen file is useless without it.

This creates two files:

- `id_ed25519` is your **private** key
- `id_ed25519.pub` is your **public** key

---

## 2. SSH Key Algorithms

| Type | Notes |
|---|---|
| **Ed25519** | Modern, fast, small, very secure. **Most used today.** |
| **RSA** | Oldest and most compatible. Use at least 3072 bits (`ssh-keygen -t rsa -b 4096`). Good for legacy systems. |
| **ECDSA** | Elliptic-curve based. Works, but many people distrust the NIST curves and prefer Ed25519. |
| **DSA** | Obsolete and insecure. Disabled in modern OpenSSH. Avoid. |
| **FIDO2** (`ed25519-sk`, `ecdsa-sk`) | The private key lives on a hardware token such as a YubiKey. The strongest option. |

---

## 3. Setting the Public Key on the Server

Since I was working on a VM, I had to place the public key on the "server" myself. I found out that SSH checks `~/.ssh/authorized_keys` in the target user's home directory, and that each line in that file is one allowed public key. So from my account, I ran the following to add my public key to the new user (`vault`):

```bash
sudo mkdir -p /home/vault/.ssh
echo "ssh-ed25519 AAAA...your-key... you@example.com" | sudo tee -a /home/vault/.ssh/authorized_keys
sudo chmod 700 /home/vault/.ssh
sudo chmod 600 /home/vault/.ssh/authorized_keys
sudo chown -R vault:vault /home/vault/.ssh
```

The line inside the quotes is the **whole contents** of my `id_ed25519.pub` file: the key type, the key itself, and the comment, all on one line.

You can double-check that it landed correctly:

```bash
sudo ls -la /home/vault/.ssh/
sudo cat /home/vault/.ssh/authorized_keys
```

### Why the permissions matter

SSH is strict on purpose. If other users can write to `.ssh` or `authorized_keys`, someone could slip in their own key. So SSH **silently ignores** the key when permissions are too loose. This is the number one reason it sometimes doesn't work.

| Path | Permission | Meaning |
|---|---|---|
| `~/.ssh/` | `700` | Only the owner can enter |
| `~/.ssh/authorized_keys` | `600` | Only the owner can read/write |
| Private key | `600` | Only the owner can read/write |

---

## 4. Connecting to the vault User

Here is the full picture of my setup:

| | Who | What they hold |
|---|---|---|
| **Client** | My original user on the VM | The **private** key (`~/.ssh/id_ed25519`) |
| **Server** | The `vault` user, on the same VM | The **public** key (in `/home/vault/.ssh/authorized_keys`) |

Because both users live on the same machine, the "server" is the VM itself. So instead of a remote IP address, I connect to `localhost`:

```bash
ssh vault@localhost
```

Here is what happens when you run it:

1. **First connection only:** SSH asks whether you trust the host's fingerprint. Type `yes`. It gets saved in `~/.ssh/known_hosts` so you won't be asked again.
2. **Passphrase prompt:** If you set a passphrase in step 1, SSH asks for it now. This unlocks *your private key*. It is not `vault`'s password (that account has none).
3. **You're in:** Your prompt changes to show you are now `vault`.

Confirm who you are, and when you're done, go back to your original user:

```bash
whoami    # prints: vault
exit      # returns to your original user
```

If my key had a custom name or location, I would have used:

```bash
ssh -i ~/.ssh/my_key vault@localhost
```

For a non-default port:

```bash
ssh -p 2222 vault@localhost
```

> **Why use SSH at all on the same machine?** I could switch users with `sudo -u vault -i`, but that skips SSH completely. Using `ssh vault@localhost` proves that key authentication works from start to finish, which is exactly what you'd rely on when connecting to a real remote server (just swap `localhost` for the server's IP or hostname).

### If you get `Permission denied (publickey)`

Check these in order:

1. Did you paste the **whole** public key line into `authorized_keys`, without line breaks?
2. Are the permissions right (`700` on `.ssh`, `600` on `authorized_keys`)?
3. Does `vault` own the files? (`sudo chown -R vault:vault /home/vault/.ssh`)
4. Run `ssh -v vault@localhost` to see detailed output about which keys SSH is trying.

---

## 5. How to Get Your Private Key for a Remote Server

When creating a lightsail VM instance for example, you can generate an SSH key pair and download the private key as a `.pem` file (e.g. `mykey.pem`). The corresponding public key is stored on the instance, while the downloaded file contains the private key you'll use to authenticate yourself.

But what exactly is a PEM file?

PEM (Privacy-Enhanced Mail) is a format used to store cryptographic data, including private keys, public keys, and certificates. A PEM file typically contains Base64-encoded data wrapped between a header and footer, like this:

```text
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA...
-----END RSA PRIVATE KEY-----
```

In this case, the file contains your private key, which SSH uses to prove your identity when connecting to the remote server.

Since this key grants access to your server, you must keep it secure. If it falls into the wrong hands, someone could potentially use it to gain unauthorised access to your instance.

To connect to your EC2 instance, first restrict access to the key file and then use it with SSH:

```bash
chmod 400 mykey.pem
ssh -i mykey.pem ec2-user@server_ip
```

The `chmod 400` command ensures that only the file owner can read the key, while the `-i` flag tells SSH which private key to use for authentication.

---

## Things I Learnt Along the Way

- The **public** key goes on the account you want to log into. The **private** key stays with the person logging in.
- Keep your private key private: `chmod 600 ~/.ssh/id_ed25519`. SSH refuses to use it otherwise.
- Treat a `.pem` private key like a password. Anyone who has it can log in.
- Wrong permissions on `.ssh` or `authorized_keys` make SSH ignore your key without telling you why.

---

## References

1. [How SSH Authentication with GitHub Works Under the Hood](https://www.freecodecamp.org/news/ssh-authentication-with-github-under-the-hood) (freeCodeCamp)
2. [Generating a new SSH key and adding it to the ssh-agent](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent) (GitHub Docs)
3. [Learn to Cloud](https://learntocloud.guide) (the course that started this)

---

*Found a mistake or have a suggestion? Leave a comment.*
