How SSH Really Works
Key Exchange, Host Keys, and the Agent-Forwarding Risk You Forgot
You type ssh web01, there is a short pause, and you have a shell. Between the keystroke and the prompt, the two sides agree on a key exchange, check the server’s identity, prove who you are without sending your key anywhere, and open an encrypted channel — in that order, every time. This post traces that sequence, shows the commands that expose each step, and ends on the one default most admins never change: agent forwarding, which hands anyone with root on a jump host the ability to authenticate as you. Main path is RHEL 9/10; the live checks below were run against OpenSSH 9.9p1 on AlmaLinux 10. All hostnames, addresses, and usernames are examples — web01.example.com, jump.example.com, 203.0.113.10 — nothing here is a real host. # = run as root, $ = run as your user.

$ ssh -vv web01.example.com 2>&1 | grep -iE 'kex|authenticity|permission denied|connection refused|timed out' # watch the handshake; the failure names itself
$ ssh -G web01.example.com | grep -iE '^(forwardagent|stricthostkeychecking|identityfile|hostname|user|port) ' # effective client config, files and defaults merged
$ ls -ld ~/.ssh ~/.ssh/authorized_keys # perms must be 700 and 600, or pubkey auth fails silently
# sshd -T | grep -iE '^(pubkeyauthentication|passwordauthentication|allowagentforwarding|permitrootlogin|maxauthtries)' # what the server actually enforces
# journalctl -u sshd --since '15 minutes ago' # the server-side reason for the refusal
$ ssh-keygen -F web01.example.com # is the host key in known_hosts, and which one
$ ssh-add -l # what the agent holds right now
$ ssh -o PreferredAuthentications=publickey web01.example.com # isolate pubkey auth from password fallback
-vv first, because it tells you which phase failed — key exchange, host-key check, or authentication — and each phase has a different fix. Client config second, because ~/.ssh/config silently overrides what you think you typed. Permissions third, because they are the most common cause of Permission denied (publickey) and the server will not tell you why. The server side last, because you only go there once you know the client is not the problem.$ ssh -vv web01.example.com 2>&1 | head -40 # -v is terse, -vv shows the negotiation, -vvv is for developers
$ ssh -V # client version; the KEX and key defaults below depend on it
SSH-2.0-OpenSSH_9.9 and the like — and disconnect immediately if either side speaks only SSH-1, which no supported OpenSSH does any more. Then key exchange: they agree on a key-exchange algorithm, a host-key algorithm, a cipher, and a MAC, and derive a shared secret and session keys. Then the client checks the server’s host key against known_hosts. Then user authentication. Then, and only then, a channel opens and your shell starts.The pause you feel is key exchange and authentication, not the network. On a LAN the whole thing is milliseconds; on a slow link the noticeable delay is almost always the client waiting on the agent or on a password prompt, not the cryptography. When a connection hangs,
-vv shows exactly which phase it is stuck in — debug1: Connecting to web01.example.com means the TCP connection, debug1: kex: algorithm means negotiation, debug1: Authenticating to web01.example.com as alice means auth. Read the last debug1 line before the hang; that is the phase that failed.Nothing before authentication is secret except the shared secret itself. The version strings, the algorithm lists, and the host key are all sent in the clear — that is by design, because none of them is useful to an attacker without the private keys. The encryption starts after key exchange, which is why a packet capture of the handshake shows the negotiation and then unreadable bytes. If you see a readable password in a capture, it is not SSH.
$ ssh -Q kex # every KEX the client supports, NOT the preference order
# sshd -T | grep kexalgorithms # the server's preference order, first entry wins
# sshd -T | grep -E '^(ciphers|macs)' # cipher and MAC order the server will negotiate
ssh -Q kex lists what the client can do, in no meaningful order. Its first entry on this box is diffie-hellman-group1-sha1, a legacy algorithm nobody should negotiate in 2026 — it is listed because it is supported, not because it is preferred. The order that matters is the server’s, from sshd -T, and the client’s own preference list, which ssh -G does not show. Do not read ssh -Q output as a ranking; it is a menu.On OpenSSH 9.9 (AlmaLinux 10), the server’s first choice is
mlkem768x25519-sha256 — a post-quantum hybrid — with curve25519-sha256 right behind it. Both are elliptic-curve Diffie-Hellman at heart: each side generates an ephemeral key pair, they exchange public halves, and each side computes the same shared secret locally. The secret itself never crosses the wire, which is the entire point. The keys are ephemeral — generated fresh for this connection and discarded when it ends — so a captured session cannot be decrypted later even if a long-term key leaks. That property is forward secrecy, and it is why SSH negotiates fresh keys per connection instead of reusing them.The cipher and MAC are agreed in the same exchange. On this box the server prefers
aes256-gcm@openssh.com and chacha20-poly1305@openssh.com — both authenticated encryption, where the cipher and the integrity check are one construction instead of two. The older aes256-ctr with a separate hmac-sha2-256-etm MAC is still offered further down the list for older clients. The -etm suffix matters: encrypt-then-MAC, where the integrity check covers the ciphertext, which is the ordering that survived cryptanalysis. A MAC without -etm is the older MAC-then-encrypt order, offered for compatibility.If the two sides share no algorithm, the connection fails here, loudly. The error is
no matching key exchange method found or no matching cipher found, and it means one side is too old or too restricted for the other. The fix is to upgrade the old side, not to re-enable the weak algorithm the new side dropped — every algorithm OpenSSH has removed was removed because it was broken, and turning it back on for one legacy host turns it back on for every host that client talks to.sshd -T | grep kexalgorithms on AlmaLinux 10 / OpenSSH 9.9p1:kexalgorithms mlkem768x25519-sha256,mlkem768nistp256-sha256,mlkem1024nistp384-sha384,curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512
$ ssh-keygen -F web01.example.com # find this host in known_hosts, and show the stored key
$ ssh-keygen -l -f /etc/ssh/ssh_host_ed25519_key.pub # on the server, as root: the fingerprint of its own host key
$ ssh-keygen -R web01.example.com # remove a host after a legitimate key change, then reconnect
$ ssh -o StrictHostKeyChecking=accept-new web01.example.com # accept unknown keys, refuse changed ones
known_hosts is your memory of it. The first time you connect, there is nothing to check against — that first connection is trust on first use, and the fingerprint the client shows you is only useful if you verify it through another channel: the console, your provisioning system, or a colleague reading it off the server. Accepting it blind is the normal case and the honest one; the protection it buys comes later, when the key changes and the client refuses to continue.REMOTE HOST IDENTIFICATION HAS CHANGED means stop, not retry. It means the key the server just presented is not the key you have on file for that name. The common benign cause is a rebuild or a reinstalled host that kept its name — and the correct response is still to verify out of band before removing the old key with ssh-keygen -R. The dangerous cause is a machine-in-the-middle, and it looks identical from the client side. There is no flag that distinguishes them; the fingerprint check against a trusted source is the only test, which is why the warning is written in capital letters.Hashed
known_hosts entries hide the hostnames, not the keys. With HashKnownHosts, each hostname is stored as a salted hash, so a stolen known_hosts file does not hand an attacker your inventory of hostnames. The keys themselves are still in the file, and ssh-keygen -F still finds them — hashing changes what a thief learns, not what the client can verify. Check your own effective value rather than assuming a default; distributions differ here.$ ssh -G web01.example.com | grep -i hashknownhosts # hashed hostnames or plain ones — check, do not assume
ssh-keyscan and paste them into known_hosts as a shortcut. ssh-keyscan trusts whatever the network hands it, which is exactly the attack the host-key check exists to stop. It is a tool for provisioning systems that verify the result, not for humans skipping the fingerprint check.$ ssh-keygen -t ed25519 -C alice@laptop # explicit type: same result on old and new OpenSSH
$ ssh-copy-id alice@web01.example.com # appends your .pub to the server's authorized_keys
$ ls -ld ~/.ssh ~/.ssh/authorized_keys # on the server: 700 and 600, or the server ignores the file
$ ssh -o PreferredAuthentications=publickey web01.example.com # prove pubkey works without password fallback
authorized_keys. The private key never crosses the network, which is why key auth survives packet capture and password auth does not. A stolen authorized_keys file is useless without the private key; a stolen private key is a skeleton key, which is why the private key gets a passphrase and the public key gets copied everywhere.The most common failure is permissions, and the server will not explain it. With
StrictModes on — the effective default on AlmaLinux 10, verified live — sshd refuses key auth if ~/.ssh is not 700, authorized_keys is not 600, or the home directory is group-writable. The client sees only Permission denied (publickey). The server logs the real reason, which is why the triage block sends you to journalctl -u sshd. Fix the permissions, do not relax StrictModes: it exists because a group-writable home directory means anyone in the group can replace authorized_keys.On OpenSSH 9.5 and later, a bare
ssh-keygen with no -t makes an Ed25519 key. That is the 9.5 release notes, confirmed live on 9.6. Ed25519 keys are 256 bits, fixed size, with short public keys — there is no key-length decision to get wrong, and -b is ignored for them.$ ssh-keygen -t ed25519 -C alice@laptop # RHEL 9: required for Ed25519; RHEL 10: the default already
$ ssh-keygen -t rsa -b 4096 -C alice@laptop # only if the far end genuinely cannot do Ed25519
authorized_keys is also where you restrict a key. A backup key that may only run one command, only from one network, and never forward an agent looks like this — one line, options first, key last:# in ~/.ssh/authorized_keys on the server, as the account owner — one line:
from="203.0.113.0/24",command="/usr/local/bin/backup",no-agent-forwarding,no-port-forwarding ssh-ed25519 AAAAC3... backup@laptop
from restriction is the one that saves you when a laptop is stolen. A key restricted to your office network does not authenticate from a coffee shop in another country, even with the private key and the passphrase. command pins the key to one program regardless of what the client asks for. restrict applies all restrictions at once — no agent forwarding, no port forwarding, no PTY, no X11 — and you then allow back only what the job needs. Keys without restrictions are root-equivalent credentials with no expiry; treat them that way, and restrict the ones that belong to automation first, because those are the ones nobody watches.$ eval "$(ssh-agent -s)" # start the agent; sets SSH_AUTH_SOCK and SSH_AGENT_PID
$ ssh-add ~/.ssh/id_ed25519 # load a key into the agent (passphrase asked once)
$ ssh-add -l # list the keys the agent holds, by fingerprint
$ ssh-add -c ~/.ssh/id_ed25519 # reload with confirmation: approve every signing request
$ echo "$SSH_AUTH_SOCK" # the socket clients use to reach the agent
$ ssh-add -D # DESTRUCTIVE to the session: removes all keys from the agent
ssh. When you type your passphrase once into ssh-add, the agent decrypts the key and keeps it. Every later connection asks the agent to sign, and the agent signs — the private key material never leaves the agent process, and no program that talks to the agent can extract it. That is the security property everyone quotes, and it is true.It is also incomplete, because signing is the capability that matters. Possessing the private key and being able to ask the agent to sign are the same thing from the server’s point of view: either way, the server sees a valid signature and opens the session. The agent protects the key from theft; it does not protect the signing capability from misuse by anyone who can reach the agent’s socket. That distinction is the whole of the next section.
ssh-add -c is the cheap mitigation most people never use. A key loaded with confirmation makes the agent ask before every signing operation — on your local machine, through your terminal or a prompt, where you can see what is being asked. It turns silent misuse into a visible prompt. It is slightly annoying, which is why it is the right default for a key that can reach production: the annoyance is the control.The agent dies with your login session, and that is a feature. Keys loaded into an agent live in memory, not on disk, and a reboot or logout clears them. If you find keys that survive a reboot, something else loaded them — check for a desktop keyring or a startup script, and decide whether you actually want that convenience. An agent that never forgets is a key without a passphrase by another name.
$ ssh -A jump.example.com # -A forwards the agent for this connection only
$ echo "$SSH_AUTH_SOCK" # on jump.example.com: the forwarded socket, /tmp/ssh-XXXX/agent.NNN
$ ssh-add -l # on jump.example.com: YOUR keys, listed from your laptop's agent
$ ssh web01.example.com # on jump.example.com: works, authenticated by your agent, through the forward
ssh -A, a process on the jump host can talk to your laptop’s agent exactly as if it were local. Your private key never crosses the wire — true, and beside the point. Anyone who can reach that socket can ask the agent to sign authentication challenges, and the server on the far end cannot tell whether the signature was requested by you or by someone else on the jump host.Root on the jump host can use your agent for as long as you are connected. Root can read any process’s environment, find
SSH_AUTH_SOCK, and point an ssh client at it. From there, every host your key can reach is reachable as you — production included — with no passphrase prompt, no second factor, and no log entry on your laptop distinguishing your signatures from theirs. The window lasts for the life of your connection, and it closes only when you disconnect. This is not a vulnerability in OpenSSH; it is the documented behaviour of forwarding, and the man page says so. It is a risk most admins accept without noticing they accepted it, usually because -A was the quickest way to hop through a bastion five years ago and nobody revisited it.The client default is safe; the server default is not. The client’s
ForwardAgent defaults to no — forwarding only happens when you ask for it with -A or set it in ~/.ssh/config. The server’s AllowAgentForwarding defaults to yes — verified live on AlmaLinux 10, where the directive is commented out in sshd_config and the effective value from sshd -T is still yes. That combination means forwarding is a client decision the server never questions, and the server you administer is currently allowing it for anyone who asks.Check what you are actually forwarding before you decide it is fine. Run
ssh -G against your jump host and look at the forwardagent line — a Host * block with ForwardAgent yes in a shared config forwards your agent to every host you touch, including the ones you would never choose to trust with it. That wildcard is the usual way this risk goes from a deliberate choice on one host to a standing condition on all of them.-A, run ssh-add -l on the jump host, and watch your own keys listed back at you. If that output does not make you slightly uncomfortable, consider who else has root on that box — and whether you would hand them your laptop unlocked.$ ssh -J jump.example.com web01.example.com # one command, no agent on the jump host
$ ssh -J jump.example.com,dmz.example.com web01.example.com # chain two jumps, still no agent exposed
Put it in
~/.ssh/config once, and stop typing -J forever:# ~/.ssh/config on your laptop — one block per target, or one wildcard for a fleet
Host web01.example.com
HostName 203.0.113.10
User alice
ProxyJump jump.example.com
ForwardAgent no
Host jump.example.com
User alice
ForwardAgent no
ForwardAgent no lines are not redundant. They are the belt to ProxyJump’s braces: they make the safe behaviour explicit, so a future edit — or a config file copied from a blog post with a Host * block — cannot silently re-enable forwarding. Config files are read top to bottom and the first matching value wins, so put the specific blocks before any wildcard block, and check the merged result with ssh -G web01.example.com after every edit. That command exists precisely because nobody can hold the merge order in their head.The one thing ProxyJump does not do is single sign-on to the target. The second hop authenticates with your agent locally — the agent runs on your laptop, the signing happens on your laptop, and only the signed challenge crosses the tunnel. That is the correct division: the jump host routes, your laptop authenticates, and nothing in between holds a credential worth stealing.
# sshd -T | grep -iE '^(passwordauthentication|permitrootlogin|allowagentforwarding|allowtcpforwarding|maxauthtries)' # the before picture
# cp /etc/ssh/sshd_config /root/sshd_config.pre-hardening # one copy, before you touch anything
sshd -T prints the effective configuration — files, drop-ins, and compiled-in defaults merged — which is the only view that matters, because the file on disk is not the configuration. AlmaLinux 10’s sshd_config includes /etc/ssh/sshd_config.d/*.conf, and a drop-in can override a line you just edited in the main file while you stare at the main file wondering why nothing changed. sshd -T is how you find out which one won.# /etc/ssh/sshd_config — the four changes, then verify before you reload
PasswordAuthentication no
PermitRootLogin prohibit-password
AllowAgentForwarding no
AllowTcpForwarding no
MaxAuthTries 3
PasswordAuthentication no is the setting that does the most work. Passwords are guessable, and the internet guesses them constantly — the threat-map feed on this site’s own server is overwhelmingly SSH password guessing, day after day. Key auth is not guessable in the same way, and turning passwords off removes the entire attack class instead of rate-limiting it. Keep one tested key-based path working before you do this, from another terminal, or you will lock yourself out of your own box and learn the value of console access the hard way.PermitRootLogin prohibit-password is the narrow setting, not no. Root may log in, but only with a key. That keeps emergency key-based root access working while removing root password guessing — which is the combination that matters, because root is the username every guessing bot tries first. AllowAgentForwarding no stops your server from being the jump host in somebody else’s forwarding mistake. AllowTcpForwarding no stops it from being a tunnel endpoint unless you need tunnels, in which case scope it with a Match block for the accounts that need it instead of leaving it open fleet-wide. MaxAuthTries 3 — down from the effective default of 6, verified live — gives a legitimate client with two keys and a typo room to work, and a guessing bot a third of the attempts per connection.Reload, do not restart — and check the syntax first:
# sshd -t # syntax check: silence means clean, anything else means fix it before you touch the service
# systemctl reload sshd # re-reads config, keeps existing sessions up
# sshd -T | grep -iE '^(passwordauthentication|permitrootlogin|allowagentforwarding|allowtcpforwarding|maxauthtries)' # the after picture
sshd -t before reload is the habit that prevents the 2am lockout. A typo in sshd_config does not fail the reload loudly — it fails the next daemon start, or worse, leaves the old config running while you believe the new one is in effect. The -t check catches it while the old daemon is still serving. Reload keeps existing sessions connected, so a mistake does not drop the terminal you are using to fix it — but it also means the session you test from must be a new connection, because your existing shell is running under the old config.$ ssh -vv web01.example.com 2>&1 | grep -i 'permission denied' # which auth methods the server offered, and which it accepted
# journalctl -u sshd --since '15 minutes ago' | grep -i 'failed\|refused\|error' # on the server: the reason, in plain words
$ ls -ld ~ ~/.ssh ~/.ssh/authorized_keys # on the server, as the account: home 755 or tighter, .ssh 700, file 600
$ ssh-keygen -l -f ~/.ssh/id_ed25519.pub # on your laptop: the fingerprint the agent should be offering
Permission denied (publickey,password) is a list, not a sentence. The methods in parentheses are the ones the server offered and you failed or did not attempt. If publickey is listed and your key was not tried, the client did not offer it — check IdentitiesOnly, check that the agent holds the key with ssh-add -l, and check that ~/.ssh/config does not point IdentityFile at a path that does not exist. If the key was offered and rejected, the problem is on the server: permissions, the wrong key in authorized_keys, or the account locked. The client cannot tell you which; the server log can.Connection refused is not an SSH problem. It means nothing is listening on port 22 — sshd is down, the host is down, or a firewall is rejecting the connection rather than dropping it. Connection timed out means the packets never arrived — routing, a firewall dropping silently, or the wrong address. Host key verification failed is step 3, above. Three different errors, three different layers, and -vv tells you which one you have before you start changing configuration to fix the wrong layer.The agent holds the wrong key more often than anyone admits.
ssh-add -l lists fingerprints; compare one against ssh-keygen -l -f ~/.ssh/id_ed25519.pub on your laptop. If the agent holds an old key from a previous job and the server only knows the new one, authentication fails with a key that works everywhere else — because everywhere else knows the old key too. ssh-add -D clears the agent, and loading only the key for this job removes the ambiguity. The server tries the offered keys in order and stops at MaxAuthTries; an agent full of stale keys burns through those attempts before the right key is ever offered, which is the quietest failure in this whole post.| I need to… | Command |
|---|---|
| Watch the handshake fail in real time | ssh -vv web01.example.com |
| See the effective client config | ssh -G web01.example.com |
| See the effective server config | sshd -T |
| List the KEX algorithms the client supports | ssh -Q kex |
| Make a new Ed25519 key | ssh-keygen -t ed25519 -C alice@laptop |
| Install my public key on a server | ssh-copy-id alice@web01.example.com |
| Check a host key is in known_hosts | ssh-keygen -F web01.example.com |
| Remove a host after a legit key change | ssh-keygen -R web01.example.com |
| Show a host key fingerprint | ssh-keygen -l -f /etc/ssh/ssh_host_ed25519_key.pub |
| Start the agent and load a key | eval "$(ssh-agent -s)" ; ssh-add ~/.ssh/id_ed25519 |
| List the keys the agent holds | ssh-add -l |
| Load a key that asks before each use | ssh-add -c ~/.ssh/id_ed25519 |
| Jump through a bastion without forwarding | ssh -J jump.example.com web01.example.com |
| Forward the agent for one connection | ssh -A jump.example.com |
| Check sshd_config syntax before reload | sshd -t |
| Apply sshd_config without dropping sessions | systemctl reload sshd |
| Read the server’s side of a refusal | journalctl -u sshd --since '15 minutes ago' |
| Fix the permissions pubkey auth needs | chmod 700 ~/.ssh ; chmod 600 ~/.ssh/authorized_keys |
-vv shows which one failed.Key exchange: ephemeral keys, shared secret never sent, forward secrecy per connection;
ssh -Q is a menu, sshd -T is the order.Host keys:
known_hosts is your memory of the server; a changed key means stop and verify, not retry.Auth: the client signs, the server verifies, the key never travels; permissions 700/600 or the server silently refuses.
Agent: signing without the key leaving the agent — but signing is the capability, and forwarding hands it to root on the jump host.
Fix: ProxyJump instead of
-A, ForwardAgent no in config, AllowAgentForwarding no on the server, passwords off.