1751 Words

🔐 2. How an SSH connection is built

← 1. The mathematics · Overview · Next: 3. OpenPGP →

In part 1 we saw the building blocks: Diffie–Hellman on elliptic curves, signatures, and the hybrid with ML-KEM. Here we follow one real connection, ssh git@github.com, from the first byte to the moment you are logged in. Every log line on this page is real output of ssh -vv (OpenSSH 10.2, November 2026), shortened.


0. Four kinds of keys

Most confusion about SSH comes from mixing up these four. Each has one job:

KeyLives whereLifetimeJob
Host keythe server, /etc/ssh/ssh_host_ed25519_keyyearsproves that the server is the server (signature)
Your user keyyour machine, ~/.ssh/id_ed25519 (or a YubiKey)yearsproves that you are you (signature)
Ephemeral key-exchange keysmemory, both sidesone connection, then thrown awayproduce the shared secret (Diffie–Hellman / ML-KEM)
Session keysmemory, both sidesuntil the next rekeyencrypt the actual traffic (symmetric)

Note what is not in this table: none of the long-term keys ever encrypts anything. Host key and user key only sign. The encryption keys come from a fresh key exchange and disappear afterwards, which gives forward secrecy: if somebody steals the server’s host key next year, your recorded session of today stays unreadable.


1. The overview

 client (you)                                             server
 ─────────────                                            ──────
 TCP connect to port 22  ───────────────────────────────▶
                         ◀──────────── "SSH-2.0-..."         ① version strings
 "SSH-2.0-OpenSSH_10.2"  ───────────────────────────────▶

 KEXINIT: my algorithms  ───────────────────────────────▶   ② negotiate
                         ◀────────── KEXINIT: my algorithms

 ephemeral public key(s) ───────────────────────────────▶   ③ key exchange
                         ◀── ephemeral public key(s)
                             + host key
                             + signature over everything     ④ server proves itself
 check host key in known_hosts                               ⑤ do I know you?
 both: K, H → session keys                                   ⑥ derive keys
 NEWKEYS                 ◀──────────────────────────────▶ NEWKEYS
 ═════════════════════ everything below is encrypted ═════════════════════
 "I am git, here is a    ───────────────────────────────▶   ⑦ user authentication
  signature with my key"
                         ◀──────────────────────── success
 open channel: shell / command / port forward               ⑧ channels

2. Step by step

① Version strings

debug1: Connecting to github.com [140.82.121.3] port 22.
debug1: Local version string SSH-2.0-OpenSSH_10.2p1 Ubuntu-2ubuntu3.8
debug1: Remote protocol version 2.0, remote software version 9f8779a8

Both sides send one line of plain text. “2.0” is the protocol version; SSH-1 is long dead. These strings are remembered, because later they are signed (step ④), so an attacker cannot quietly change them.

② Negotiation: KEXINIT

Both sides send a list of what they support, in order of preference: key exchange methods, host key types, ciphers, MACs. For each category the first algorithm on the client’s list that the server also supports wins.

debug2: KEX algorithms: mlkem768x25519-sha256,sntrup761x25519-sha512,...,curve25519-sha256,...,kex-strict-c-v00@openssh.com
debug1: kex: algorithm: mlkem768x25519-sha256
debug1: kex: host key algorithm: ssh-ed25519
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none

So this connection uses:

  • mlkem768x25519-sha256: the hybrid key exchange from part 1, §8: X25519 (elliptic-curve Diffie–Hellman) and ML-KEM-768 (post-quantum), hashed together with SHA-256. Default since OpenSSH 10.0 (2025).
  • ssh-ed25519: the server will sign with an Ed25519 host key.
  • chacha20-poly1305@openssh.com: the symmetric cipher for the data, with built-in integrity check (that is why the MAC is “implicit”).

The odd entry kex-strict-c-v00@openssh.com is not an algorithm but a flag: “strict key exchange”, added in 2023 against the Terrapin attack, in which an attacker could silently delete a message during the handshake.

See your own lists with ssh -Q kex, ssh -Q cipher and ssh -Q key.

③ The key exchange

With plain X25519 (curve25519-sha256), this is exactly the ECDH of part 1, §5.4, on Curve25519:

clientserver
random secret$c$ (32 bytes)$s$ (32 bytes)
sends$Q_C = c \cdot G$$Q_S = s \cdot G$
calculates$K = c \cdot Q_S$$K = s \cdot Q_C$

Both get the same point, $K = csG$, and nobody on the line can calculate it.

With the hybrid mlkem768x25519-sha256, the client sends two things in one message: an X25519 public key (32 bytes) and an ML-KEM-768 public key (1,184 bytes). The server:

  • does the X25519 calculation as above, and
  • uses the ML-KEM key to encapsulate a fresh random secret: it sends back a ciphertext (1,088 bytes) that only the client can open.

Both sides end up with two secrets and combine them:

$$K = \mathrm{SHA256}\left(K_{\mathrm{ML\text{-}KEM}} \,\|\, K_{\mathrm{X25519}}\right)$$

An attacker has to break both to get $K$: X25519 protects against weaknesses in the young ML-KEM, ML-KEM protects against a future quantum computer.

④ The server proves who it is

The key exchange alone is anonymous: a man in the middle could do one exchange with you and another with the server (part 1, §4). So the server proves its identity by signing the whole conversation so far.

Both sides calculate the exchange hash $H$ over everything that happened:

$$H = \mathrm{HASH}\left(V_C \,\|\, V_S \,\|\, I_C \,\|\, I_S \,\|\, K_S \,\|\, Q_C \,\|\, Q_S \,\|\, K\right)$$
$V_C, V_S$the two version strings (step ①)
$I_C, I_S$the two KEXINIT messages, all algorithm lists (step ②)
$K_S$the server’s public host key
$Q_C, Q_S$the two ephemeral public keys (step ③)
$K$the shared secret

The server signs $H$ with its private host key (Ed25519, part 1, §6) and sends: its public host key $K_S$, its $Q_S$, and the signature.

The client calculates the same $H$ and checks the signature with $K_S$. Because $H$ contains $K$, the signature is only valid for this key exchange. A man in the middle has a different $K$ with each side, and he cannot produce the server’s signature over his own $H$ without the server’s private key.

debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ssh-ed25519 SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU

⑤ Do I know this server? (known_hosts)

The signature proves that the other side owns the private key belonging to $K_S$. But is $K_S$ really GitHub’s key? SSH has no certificate authority (unlike TLS). It uses trust on first use:

  • The first time, ssh shows the fingerprint (SHA256:+DiY3wvv..., a hash of the public host key) and asks whether you trust it. Compare it with a source you trust: GitHub publishes its fingerprints on its website, and for your own servers you check it on the server with ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub.
  • Then it is stored in ~/.ssh/known_hosts.
  • Every next time it must match:
debug1: Host 'github.com' is known and matches the ED25519 host key.

If it does not match, you get the big REMOTE HOST IDENTIFICATION HAS CHANGED! warning, and ssh refuses. That is either a reinstalled server, or exactly the man-in-the-middle attack this whole step exists to stop. Never “just remove the line” without finding out which.

⑥ From one secret to six keys

The first $H$ of a connection also becomes the session identifier. From $K$ and $H$ both sides derive six keys with the same hash function, each with its own letter:

$$\text{key}_X = \mathrm{HASH}\left(K \,\|\, H \,\|\, X \,\|\, \text{session\_id}\right), \qquad X \in \{\text{A},\text{B},\text{C},\text{D},\text{E},\text{F}\}$$
LetterKey
A / Binitial counter (IV), client→server / server→client
C / Dencryption key, client→server / server→client
E / Fintegrity (MAC) key, client→server / server→client

Each direction has its own keys. Then both sides send NEWKEYS, and from that moment everything is encrypted:

debug1: rekey out after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: SSH2_MSG_NEWKEYS received

The “rekey” line: after about 1 GB of data (or an hour) the whole key exchange is done again, inside the encrypted connection, so no single key protects too much traffic.

⑦ You prove who you are

Now the server knows it has a secret channel, but not with whom. Your turn:

debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey

With public-key authentication:

  1. The client asks: “Would you accept this public key for user git?” The server looks it up in ~/.ssh/authorized_keys (GitHub: in the keys of your account).
  2. If yes, the client signs a message containing:
$$\text{session\_id} \,\|\, \text{user} \,\|\, \text{service} \,\|\, \text{"publickey"} \,\|\, \text{algorithm} \,\|\, \text{your public key}$$
  1. The server checks the signature with the public key from authorized_keys.

Three things to notice:

  • Your private key never leaves your machine. Only a signature goes over the line. Even a malicious server learns nothing it could use elsewhere.
  • The signature contains the session identifier, which is unique to this connection (it contains this connection’s $K$). A recorded signature is useless for any other connection, so it cannot be replayed.
  • Who makes the signature does not matter to the protocol. It can be the ssh program reading ~/.ssh/id_ed25519, the ssh-agent holding the key in memory, gpg-agent with a key on a smart card (YubiKey OpenPGP), or a FIDO2 key that only signs after you touch it (sk-ssh-ed25519, YubiKey FIDO2). The YubiKey simply calculates the signature from step 2 inside the chip.

The server tells you which signature types it accepts:

debug1: kex_ext_info_client_parse: server-sig-algs=<...,sk-ssh-ed25519@openssh.com,...,ssh-ed25519,ecdsa-sha2-nistp256,rsa-sha2-512,rsa-sha2-256,ssh-rsa>

Note rsa-sha2-256 / rsa-sha2-512 next to plain ssh-rsa: an RSA key is still fine, but the old ssh-rsa signature uses SHA-1 and is disabled by default since OpenSSH 8.8.

Password login also happens here, inside the encrypted channel, so the password is not visible on the line. But the server sees it in plain text, and anybody can try to guess it. That is why hardening turns it off.

⑧ Channels

Once logged in, everything runs in channels inside the one encrypted connection: your shell, a command, scp/sftp, port forwards (-L, -R, -D), agent forwarding. One key exchange protects them all.


3. What protects against what

AttackStopped by
Listening on the linekey exchange (③) + symmetric encryption (⑥)
Recording now, stealing keys laterephemeral keys, thrown away (forward secrecy)
Recording now, quantum computer laterML-KEM in the hybrid key exchange
Man in the middlehost key signature over $H$ (④) + known_hosts (⑤)
Changing or deleting packetsintegrity check (Poly1305 / MAC) + strict kex
Replaying your loginsession identifier inside your signature (⑦)
Stolen passwordno passwords: keys only, on a hardware token

4. See it yourself

ssh -vv user@host                 # the whole handshake (add -vvv for even more)
ssh -Q kex                        # key exchange methods your client knows
ssh -G host | grep -i -E '^(kexalgorithms|hostkeyalgorithms|ciphers)'   # what it will offer to this host
ssh-keyscan -t ed25519 host       # a server's public host key
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub   # its fingerprint (on the server)
ssh-keygen -lf ~/.ssh/id_ed25519.pub               # your key's fingerprint

Related notes: generate a key · ~/.ssh/config · file permissions · server hardening · YubiKey for SSH

Sources

  • RFC 4253 (SSH transport: version exchange, KEXINIT, exchange hash, key derivation), RFC 4252 (user authentication), RFC 5656 (elliptic-curve key exchange), RFC 8731 (curve25519-sha256).
  • OpenSSH release notes: 9.0 (sntrup761x25519 default), 9.6 (strict kex, Terrapin), 10.0 (mlkem768x25519-sha256 default).
  • IETF draft PQ/T Hybrid Key Exchange with ML-KEM in SSH (mlkem768x25519-sha256).