Josh's Toolbox

How SSH Initializes Connections

Today I want to show how an SSH connection is formed, from the first request till your session, usually a shell prompt, is established. By the end, hopefully the secrets of ssh -v are demystified.

AI Disclosure: This text is mine, but I did use Claude to fill in some of the gaps in my memory.

With all the rumors around cryptographic algorithms being broken, lots of people are asking how they can create new keys to make sure their connections are secure. The short and slightly misleading answer is: you don’t; your keys aren’t involved in the encrypted communication between yourself and the target server, they just establish your identity. For a slightly longer answer, I recommend Paul Bauer’s blog post which provides short guidance from a GitHub perspective, though the advice applies to your SSH key management generally.

The even longer answer I am sharing here goes deep into how the SSH protocol establishes a connection so you can understand why changing your keys probably isn’t the response you think it is, where the answer to guaranteeing connection encryption lies, and what all that noise is when you accidentally (or intentionally) pass -v to ssh.

Command Invocation

We’ll start with the example ssh invocation the rest of the post references:

> ssh -v -o ControlPath=none 192.168.42.42

-o ControlPath=none just makes sure that we are initializing a new connection. The ControlMaster feature of ssh is a mechanism to reuse a connection to the target server so you don’t have to make a new connection every time you want to talk to a target server. It’s worth its own blog post, but I put it here for people that are using it to ensure a new connection is established. If you’re not, you can find more information in the man page: man 5 ssh_config

192.168.42.42 is the server you’re hypothetically connecting to, and while these log lines came from a real invocation, this is not the IP address I used. (You don’t need to know my network map.) Sometimes you’ll pass a domain or a host specified in your SSH config ( ~/.ssh/config). The important part is that it is running an SSH server and that SSH can map that identifier to an IP address.

Reading your Configuration

debug1: Reading configuration data /home/josh/.ssh/config
debug1: /home/josh/.ssh/config line 99: Applying options for *
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: include /etc/ssh/ssh_config.d/*.conf matched no files
debug1: /etc/ssh/ssh_config line 21: Applying options for *

To start, ssh reads your configuration files to determine what options it should setup the connection with. In my case, I have some global rules showing up in Applying options for * but you might also see more specific rules like that would be identified like so:

debug1: /home/josh/.ssh/config line 99: Applying options for github.com

The Initial Connection

debug1: Connecting to 192.168.42.42 [192.168.42.42] port 22.
debug1: Connection established.

ssh then begins communication to the server. It instructs the kernel to create a TCP connection between you and the target server. Because the target server’s ssh daemon has told its kernel that it wants to listen for TCP connections on the target port ( 22 by default) and the firewall there doesn’t block traffic, the TCP connection here is successfully established. At this point, you can talk to the server, but everything you send is readable by every piece of networking equipment between the two of you. It will be a fair bit before data is encrypted and protected.

Trading Program Information

debug1: identity file /home/josh/.ssh/id_rsa type 0
debug1: identity file /home/josh/.ssh/id_rsa-cert type -1
debug1: identity file /home/josh/.ssh/id_ed25519 type 3
debug1: identity file /home/josh/.ssh/id_ed25519-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.20
debug1: Remote protocol version 2.0, remote software version OpenSSH_10.6
debug1: compat_banner: match: OpenSSH_10.6 pat OpenSSH* compat 0x04000000

Next, ssh starts looking at the keys the client be using to prove its identity, but those won’t come up till later. But, since we’re here, they indicate the path and a number indicating their key type. The negative numbers indicate there was an error, and in this case it’s because those files don’t exist.

The version log lines are the only lines that demonstrate communication between you and the server. Both you and the server send each other your version strings as soon as the connection is established. This let’s you both make intelligent decisions about what features to use, especially in the case where either side knows there’s a bug in the other’s program and version. The last line is your client announcing how it is responding to the version string it received.

Negotiating Algorithms

debug1: Authenticating to 192.168.42.42:22 as 'batman'
debug1: load_hostkeys: fopen /home/josh/.ssh/known_hosts2: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts2: No such file or directory
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: sntrup761x25519-sha512@openssh.com
debug1: kex: host key algorithm: ssh-ed25519
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none

Next, the two of you will share what algorithms you will use for the connection: which one will encrypt connection, the method to share the secrets that form that connection, and how the server will be proving its identity.

The first line tells us the IP address, port, and user you’ll be authenticating as. If you specified a domain, that would show up instead of the IP address. The user has no bearing yet, and the address and port have already been used to establish the TCP connection. This is a kind of header for everything SSH will be doing from here on out.

The next lines are the result of SSH checking out the public keys it knows for the server. In this case we just see the side-effects of the client being configured to look at files that don’t exist. But, if it finds any keys, it will tell the server about those algorithms so it can verify the server’s identity with information it has.

The interesting part starts next. KEXINIT, or key exchange initialization, messages contain the algorithms we talked about. The client announces that it has sent is and that it received ones from the server. In theory this messages and the last can be sent without waiting for the version exchange, but in practice, clients and servers will wait, that way they won’t announce algorithms they know are broken in the other’s versions.

At this debug level, you won’t see all the algorithms both sides announce, but you will see which algorithms they agree to, namely, the first algorithm in the client’s list that the server also announces.

The first kex line establishes what algorithms will be used to exchange and derive the secret materials that will serve as the basis for the long term encryption of the connection. sntrup761x25519 is what’s called hybrid key exchange that combines post-quantum and classical algorithms. We’ll talk about this one in particular a bit later. Suffice to say, it uses two algorithms with two different secrets and is considered safe for the present and quantum world. sha512 is a cryptographic hash algorithm that will be used in a couple of places.

The second line is the algorithm the server will use to prove its identity. In the example, you can see the host is proving its identity with an elliptic curve algorithm, which is one of the algorithms it has an host key for the target server. Those have been rumored to be broken and so I should probably configure that server to stop advertising that algorithm (don’t worry, I did), but as we’ll see it at least does not impact forward secrecy, cracking it does not leak old traffic.

The last two lines establish what algorithms will encrypt traffic in each direction. They will be encrypted based with different keys derived from the secret material shared via the algorithm from the first line.

Now, let’s see how these strings result in something useful.

Sharing THE Secret

debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: SSH2_MSG_KEX_ECDH_REPLY received

These lines are where the magic happens, where you and the server agree on a shared secret to encrypt your communication with and the server demonstrates its identity.

Let’s take a short detour to talk about symmetric and asymmetric encryption.

Symmetric encryption depends on a secret both sides of the communication know, like a decoder ring: you both set your decoder rings to the same setting and each of you can read what either of your have encoded. Symmetric encryption and decryption is fast (relatively) and algorithms are designed to work on data of arbitrary size. The one’s SSH uses are designed to work in a streaming fashion, so you don’t need the entire contents of your message to start encrypting early parts.

Asymmetric encryption work like a lock (public key) and key (private key). You can give the world as many copies of your lock, but only your key can unlock whatever people lock up. It’s a neat benefit, but asymmetric algorithms are slow and can only work on small sets of data, correlated with the key size.

Those differences inform how SSH connections establish a shared secret. It can’t use asymmetric encryption for on-going communication, so they need to agree on a symmetric key.

We mentioned earlier that For establishing a shared secret for the sntrup761 part of our algorithm, your client generates a one-time use public/private keypair and sends the public key off to the server. For the x25519 part, it will generate a [Diffie-Hellman keypair], which we'll cover shortly, and send the public key along with sntrup761` one. That first log line is the client announcing it has done so and is waiting for the server to respond.

The server takes that sntrup761 key and uses it to encrypt a randomly generated secret, called “THE Secret” in this sections title, what we called secret(s) previously, and usually helpfully named K_PQ, or key post-**quantum. by cryptographers. It will also generate its own Diffie-Helman keypair. The server will include K_PQ encrypted with the client’s public key in the return message, the its public Diffie-Hellman key, it’s own public key to establish its identity, and a signature of all of the messages up to now using that public key’s private key.

This signature is the critical part that proves the server is who it says it is. You’ve almost certainly seen a message like this pop up:

The authenticity of host 'github.com (140.82.113.3)' can't be established.
ED25519 key fingerprint is SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])?

This is that public key, and if you associate the incorrect key with the host, the owner of that key can sit in between the two of you, impersonating your target by rewriting messages in between. If you have the correct host key for the target, someone in the middle can’t pretend to be them because they likely wouldn’t return a key you have and without cracking the key, they can’t forge the signature.

While we’re here, let’s continue on the scenic route and talk briefly about signatures, using RSA’s scheme as an example. (Elliptic curves work differently.) Earlier, we used the lock and key analogy to describe asymmetric encryption. But, these are just numbers. If we were to switch their roles and encrypt a message with our private key (remember, normally the public key would encrypt the message so the private key holder can read it) anyone with the public key can now read it. That’s not useful for sending secrets, but unlocking it and seeing a message the keypair owner is claiming to provide proves that the contents came from the holder of the private key.

There is one problem though: we need to sign all the communication we’ve seen thus far, and asymmetric keys are limited in what size of data they can encrypt. So, we hash all the messages and do the “encryption” on that hash. Both sides have their perception of the communication stream, so the client will just compare the hash they “decrypt” from the server against the messages they’ve sent. That is one place where the hashing algorithm (sha512) comes in. It securely reduces the input to something asymmetric keys can work with.

In summation, at this point, the server sends the client:

From here, getting K_PQ is just straightforwardly decrypting the message with your private key. But the x25519 portion is not so obvious. The magic is in the algorithm and the way it works is that your public key combined with their private key results in the same value as your private key and their public key. Since private keys are never sent, there’s not enough information for an attacker to deduce this secret. (There’s a third thing mixed in to those combinations that makes the math work, and that comes straight from the x25519 definition.) This complete mix is called K_CL, or key classical. And K_PQ and K_CL’s combine their powers (or conccatenated and hashed) to create K, or key.

And all of that is captured by the second log line.

Verifying the Server Identity

debug1: Server host key: ssh-ed25519 SHA256:l9ubCSX/vzqE0vHsIFzWgrJPO6QeiRjL4XV3AtW9TyE
debug1: load_hostkeys: fopen /home/josh/.ssh/known_hosts2: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts: No such file or directory
debug1: load_hostkeys: fopen /etc/ssh/ssh_known_hosts2: No such file or directory
debug1: Host '192.168.42.42' is known and matches the ED25519 host key.
debug1: Found key in /home/josh/.ssh/known_hosts:31

With the short message you got from the server, your client compares the provided key to those it has saved. If it matches, the connection continues. If it has keys and it doesn’t match, alarm bells should go off in your head. In the innocuous case, the server may have rotated its keys or been replaced. Or, it could mean someone is intercepting your communication. When this happens, do research or ideally talk to the admin of the server directly. The dangerous and worst case scenario is someone attempting to impersonate the server.

But, if you don’t have any keys or the server yet, you can’t check any of this. You could try and get them out of band. Or, as SSH allows, just believe what the server has told you going forward.

Are you sure you want to continue connecting (yes/no/[fingerprint])? yes

With the public key approved, your client verifies that the public key generated the signature messages it has seen. An error here almost certainly means there is a network issue or bug because a man-in-the-middle attack wouldn’t be so poorly executed. Whatever is happening, the verification fails and you’ll have to try again or figure out what is going on.

Encryption!

debug1: ssh_packet_send2_wrapped: resetting send seqnr 3
debug1: rekey out after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: Sending SSH2_MSG_EXT_INFO
debug1: expecting SSH2_MSG_NEWKEYS
debug1: ssh_packet_read_poll2: resetting read seqnr 3
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey in after 134217728 blocks
debug1: SSH2_MSG_EXT_INFO received

At this point you are ready to start encrypting you communication. These next lines capture that switch-over, but are best approached out of order.

debug1: ssh_packet_send2_wrapped: resetting send seqnr 3
debug1: ssh_packet_read_poll2: resetting read seqnr 3

SSH indexes messages and feeds that number into the messages it sends to ensure that no messages are lost or injected. After encryption starts, it start the counter back over to prevent Terrapin attacks and this log line indicates it is taking that action and shows that you are protected.

debug1: rekey out after 134217728 blocks
debug1: rekey in after 134217728 blocks

Here, the client logs how many blocks (the unit of data symmetric algorithms operate on) it will see in each direction before it asks the server to negotiate new keys. The server will have its own limit that you don’t now. Either side can demand renegotiation whenever they feel like it so it doesn’t matter if you agree.

debug1: SSH2_MSG_NEWKEYS sent
debug1: SSH2_MSG_NEWKEYS received

The lines were not the result of communication between you and the server. These are the next and last messages sent unencrypted by you and the server. They simply say that future communication from then on will be encrypted on the respective ends. Since, he log messages we explored before now involved no network traffic, these are the very next messages after the server sent that three part message.

A quick note, these streams don’t directly use the agreed upon secret material (K) to encrypt communication. Reusing the same parameters in symmetric algorithms is a big no-no as having two sets of data, especially correlated data, encrypted with the same paramaters makes them very crackable. To avoid this, both sides concatenate the secret material with separate, deterministic, protocol (ssh) defined data, and hash that to determine the real on the wire secrets. The protocol defines how to do this for however many secrets the communication encryption algorithm needs to encrypt and protect traffic.

Encryption alone isn’t sufficient to provide a reliable, snoop-proof line of communication. Algorithms will incorporate other inputs and outputs to ensure things like tampering are detectable and that attacks similar dictionary attacks are effectively impossible.

The Client’s Identity

debug1: Sending SSH2_MSG_EXT_INFO
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_ext_info_client_parse: server-sig-algs=<ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ssh-ed25519@openssh.com,sk-ecdsa-sha2-nistp256@openssh.com,rsa-sha2-512,rsa-sha2-256,ssh-mldsa44-ed25519,webauthn-sk-ecdsa-sha2-nistp256@openssh.com>
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Next authentication method: publickey
debug1: get_agent_identities: bound agent to hostkey
debug1: get_agent_identities: agent returned 7 keys
debug1: Will attempt key: /home/josh/.ssh/id_rsa RSA SHA256:M8ZKjrbTOGUL1T19/nx+UHZJUUEaM5m4mtmyb7p4QhU explicit agent
debug1: Will attempt key: /home/josh/.ssh/id_ed25519 ED25519 SHA256:D/aER+EXjHy6k4LMvVoELDHdelhLFTT2JB3bOOZHtMo explicit agent
debug1: Offering public key: /home/josh/.ssh/id_rsa RSA SHA256:M8ZKjrbTOGUL1T19/nx+UHZJUUEaM5m4mtmyb7p4QhU explicit agent
debug1: Server accepts key: /home/josh/.ssh/id_rsa RSA SHA256:M8ZKjrbTOGUL1T19/nx+UHZJUUEaM5m4mtmyb7p4QhU explicit agent
Authenticated to 192.168.42.42 ([192.168.42.42]:22) using "publickey".

Up until this point, the client has never said anything about who you are. A secure stream with the target server has been established with just IP addresses, port numbers, and the server’s identity. And that last part was just for ensuring the client is talking to who it thinks it’s talking to. Cracking it would allow impersonation, but not decryption of the stream without being in between you and the server.

Technically the server’s public key is part of making the secret material providing a redundant prevention of MITM attacks, but it doesn’t have real bearing on the cryptographic security of the encrypted stream.

Your public key will be used in a similar fashion for identity verification, but with an even more impossibility of breakages of its algorithm cracking the stream: it hasn’t been used at all yet so how could it compromise the stream? It’s not a part of its security.

While signing as a method of identity verification was always a part of SSH, the first versions had very crappy algorithms. To accomodate moving to future more secure versions, new public key authentication algorithms are advertised through SSH’s extensions support. That’s why the next line with accepted key algorithms is marked by that extensibility point: kex_ext_info , or key exchange extension information (even though some extensions aren’t involved in the key exchange, like what we’re talking about here).

The line after that tells your client how the server can verify your identity. It actually got that line by attempting to provide no proof of identity. You might note that some fool has left keyboard-interactive enabled on their server instead of just key based authentication. (That fool is me.) If key-based authentication failed, the server would ask a connector to type a password. Luckily for said fool, none of the example server’s accounts have passwords so that form of authentication can never succeed, but they should shore it up anyway.

keyboard-interactive does not just mean passwords (e.g., one-time passcodes could be used), but for this server it does.

As the client, the client gets to choose which method you want to try, and in this example, the default PreferredAuthentications setting tells us to go with public key authentication.

The next lines brings a new program into play, ssh-agent. The ssh client does not have to handle your keys directly. Instead, it can interact with a separate program to discover keys and sign messages. The agent here has 7 keys, But, ssh has been configured with IdentitiesOnly=yes so it will only used the keys specified by IdentityFile in the configuration.

The client will send the key and if the server accepts, ask the agent to sign a message containing information about the connection. This signature proves your identity to the server and is forwarded on to do just that. After that proof is acknowledged, we get the only debug log line not prepended with debug1:

Authenticated to 192.168.42.42 ([192.168.42.42]:22) using "publickey".

We’re in. Ish.

This agent and client separation lets an entirely different program handle identities, like a password manager application handling your SSH keys for you. Communication between the client and agent happens over a socket allowing tons of flexibility: as long as the other side knows how to speak the agent protocol it can be whatever. It could even be you on a keyboard (but don’t do that).

Almost There

debug1: channel 0: new session [client-session] (inactive timeout: 0)
debug1: Entering interactive session.
debug1: pledge: filesystem
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug1: client_input_hostkeys: convert key: unknown or unsupported key type
debug1: client_input_hostkeys: searching /home/josh/.ssh/known_hosts for 192.168.42.42 / (none)
debug1: client_input_hostkeys: searching /home/josh/.ssh/known_hosts2 for 192.168.42.42 / (none)
debug1: client_input_hostkeys: hostkeys file /home/josh/.ssh/known_hosts2 does not exist
debug1: client_input_hostkeys: no new or deprecated keys from server
debug1: Remote: /etc/ssh/authorized_keys.d/batman:1: key options: agent-forwarding port-forwarding pty user-rc x11-forwarding
debug1: Remote: /etc/ssh/authorized_keys.d/batman:1: key options: agent-forwarding port-forwarding pty user-rc x11-forwarding

Now that everyone has agreed that everyone is who they say they are and the communication stream is secure, SSH gets to doing useful stuff.

The first line talks about a channel. Channels are identifiers that let a single SSH connection be used for multiple things. The long ago aside on ControlMaster functionality depends on this so your single connection to the server allows you to open tons and tons of shell sessions with a single connection. Otherwise you would limit yourself to around 28000 connections by default.

That limit comes from the outbound ports you can use, viewable through sysctl net.ipv4.ip_local_port_range.

In this example, there is no multiplexing, so there’s only channel 0 for the session we’ve established. In a multiplexed connection, you’d seem something like:

debug1: channel 0: new mux listener [/home/josh/.ssh/_control/47a013e660d408619d894b20806b1d5086aab03b] (inactive timeout: 0)

And lines later on talking about other channels, being used for multiplexing.

The next line announces that the session has begun. And the pledge line after that announces what permissions the client-side SSH sandbox will have for interacting with the session. In this case, it needs filesystem access because the connection will be updating your local public keys for the target server.

If you had passed -o UpdateHostKeys=no, the sandbox you interact with the external server in would have the minimal network and terminal permissions, announced as pledge: network.

pledge isn’t actually supported on Linux and is a BSD concept, so we don’t actually end up doing anything special.

Since UpdateHostKeys=no isn’t set, and this server was trusted before this connection (i.e., we didn’t get the prompt asking us to trust the key) , the next lines are the host sending the client all of its keys and the client saving them. This way, if the server has more keys, future client connections can use those to identify the server. Since it knows it is really talking to the server, it knows they are valid for the server. This is especially useful as new key types are supported by the server software, a distinct possibility especially today. In this example, we can see there are no new keys, but there is a new key type the client doesn’t support.

The next two lines were actually generated by the server earlier in the transaction but are displayed now. They’re the matching line for your key on the target server and are displayed twice because that file was parsed twice: once when you offered your key, then again when your signature proved you had the key. Your client can use this information to intelligently leverage or inform you of functionality or lack thereof.

Finally

debug1: Sending environment.
debug1: channel 0: setting env LANG = "en_US.UTF-8"
batman@thecave:~]>

Now, we are finally ready for SSH to do its terminal stuff. Your client sends on the environment variables you invoked SSH with. In this example, the client is configured to only send one specific environment variable LANG. That’s good, the server doesn’t need to know all the nonsense going on in your environment, private or otherwise.

With this, the server provisions a terminal for you and launches your login shell. Without the -v all you would have seen is the prompt. That verbosity flag shows us that so much happens to set up the connection.

And now, hopefully you understand why your SSH key algorithm is not (the only place) where you go to secure your traffic. Yes, cracking the algorithm behind it does mean that someone can impersonate you and do bad things. But, in theory that isn’t actively being exploited. And the contents of your past and ongoing SSH communications are not impacted since the confidentiality of the encryption of your communications is not derived from your key. So, someone who has captured all of the traffic between you and the server still doesn’t know what you said.

So, definitely move your allegedly weakened 256-bit elliptic curve keys to ECDSA NISTP384 or RSA-3072 or higher.

# ECDSA
ssh-keygen -t ecdsa -b 384
# RSA
ssh-keygen -t rsa -b 3072

But now you know that the encrypted stream between your client and server is a property of the software, not your keys. Make sure your client and server software are up-to-date. And make sure those algorithms captured in the key exchange lines are quantum safe. And if you don’t have control over the server software, feel free to cry.

Bonus: Tunneling

If you were doing something else like tunneling traffic through the server to a different, your last two log lines would look different. In fact, they wouldn’t be there at all. And you wouldn’t get a prompt. Give it a try yourself:

# Tunneling a request to this blog through 192.168.42.42
ssh -L 8675:joshstoolbox.com:443 -N 192.168.42.42
curl --connect-to joshstoolbox.com:443:localhost:8675 \
    https://joshstoolbox.com