Chapters

SSH & tunnels

As Kadé's engineer you log in to kade-api to read logs, and you need to query kade-db, which has no public address at all. SSH does both: a secure remote shell, and encrypted tunnels that carry other connections through it. This chapter covers how SSH works, keys, the three kinds of tunnels, and how GCP lets you reach VMs without opening port 22 to the internet.

Application protocols · chapter 29 of 34 · 8 min read

What SSH is

SSH (Secure Shell) gives you an encrypted, authenticated connection to another machine over an untrusted network. It replaced telnet and rsh, which sent everything, passwords included, as plain text. It runs over TCP port 22 and does much more than a shell:

Remote shellssh thirana@kade-api
Run one commandssh kade-api 'journalctl -u kade-api -n 50'
Copy filesscp, sftp, rsync -e ssh
Gitgit@github.com:kade/kade-api.git
TunnelsCarry other TCP connections through the encrypted link (section 8)

Three layers inside SSH

#LayerJobCompare with
1TransportKey exchange, server authentication (host key), encryption and integrityWhat TLS does for HTTPS (chapter 25)
2User authenticationProves who you are: public key, password, or othersHTTPS usually leaves this to the app (login, tokens)
3ConnectionMany channels over one connection: a shell, a file copy, several tunnels at onceHTTP/2 streams (chapter 24)

Connecting, step by step

Laptopkade-api :22after the TCP handshakeSSH-2.0-OpenSSH_9.6SSH-2.0-OpenSSH_9.6KEXINIT: the algorithms I supportKEXINITECDH key shareECDH key share + host key + signaturethe client checks the host key against known_hostsencrypted: user authentication (public key)encrypted: successencrypted: open a session channel → shell
1After the TCP handshake, both sides send a version line in plain text, e.g. SSH-2.0-OpenSSH_9.6.
2KEXINIT: each lists the algorithms it supports (key exchange, host key types, ciphers, MACs); the first match on both lists wins.
3Key exchange: an elliptic-curve Diffie-Hellman (usually curve25519), exactly the idea from chapter 25. Both sides get a shared secret and a session ID.
4The server signs the exchange with its host key. The client checks the signature and whether it knows this host key (section 4). Everything from here on is encrypted.
5User authentication: the client proves it holds your private key (section 5).
6The client opens a session channel and asks for a shell (or a command, or a tunnel).

Host keys and "trust on first use"

HTTPS proves the server's identity with a certificate signed by a CA (chapter 25). Plain SSH has no CA. Instead, on the first connection it shows you the server's host key fingerprint and asks:

The authenticity of host 'kade-api (10.10.1.10)' can't be established.
ED25519 key fingerprint is SHA256:q3Hk2Y0lK8vJb9nX7yWm1cR4tA5sD6fG8hJ0kL2mN4o.
Are you sure you want to continue connecting (yes/no/[fingerprint])?

Answer yes, and the key is saved in ~/.ssh/known_hosts. Every later connection must present the same key. This model is called trust on first use (TOFU): the first connection is the weak moment, so verify the fingerprint through another channel if it matters.

Proving who you are: keys

Passwords work but can be guessed and phished, and bots try them on every server with port 22 open. Public-key authentication is the standard: you keep a private key, and the server holds your public key in ~/.ssh/authorized_keys.

Laptop (holds the private key)kade-api (authorized_keys)"I can use this public key: ssh-ed25519 AAAAC3Nz…""that key is in authorized_keys: prove you hold it"signature over this session's ID, made with the private keykade-api checks the signature with the public keyauthenticated
  • The private key never leaves your laptop. You prove you hold it by signing this connection's unique session ID. A recorded signature is useless for any other connection.
  • Key type: use ed25519: short, fast and safe. RSA needs at least 3072 bits.
  • Protect the private key with a passphrase, and let ssh-agent hold it unlocked for the day. Hardware keys (YubiKey, with ed25519-sk) keep it on a device that cannot be copied.
  • Agent forwarding (ssh -A) lets a remote machine use your agent. Anyone with root there can use your keys while you are connected. Prefer ProxyJump (section 9).

Managing keys and config

ssh-keygen -t ed25519 -C "thirana@kade.lk"   # creates ~/.ssh/id_ed25519 (private) and .pub (public)chmod 600 ~/.ssh/id_ed25519                   # SSH refuses private keys others can read

A ~/.ssh/config file saves typing and keeps settings in one place:

Host kade-api
    HostName 34.87.120.15
    User thirana
    IdentityFile ~/.ssh/id_ed25519
    ServerAliveInterval 30        # keepalive: survive NAT and firewall idle timeouts (chapter 21)

Host kade-db
    HostName 10.10.2.5            # private IP: reachable only through kade-api
    User thirana
    ProxyJump kade-api            # section 9

One key per person, never shared; remove a person's public key when they leave. The ControlMaster option can reuse one connection for many ssh commands (like HTTP keep-alive), which makes repeated commands instant.

Channels: many things over one connection

After login, everything runs as a channel inside the one encrypted TCP connection: your shell is one channel, a file copy another, and each tunnel connection another. This is how one SSH login can carry a shell and three tunnels at once.

Tunnels: port forwarding

A tunnel takes a TCP connection on one side and carries it, inside SSH, to the other side. There are three kinds:

#KindFlagDirectionKadé example
1Local-LA port on your laptop leads to something the server can reachOpen kade-db's PostgreSQL (private, 10.10.2.5:5432) as localhost:5433 on your laptop
2Remote-RA port on the server leads back to something your laptop can reachShow a teammate the Node app running on your laptop's port 3000 (the reverse tunnel from chapter 10)
3Dynamic-DA SOCKS proxy on your laptop; each app connection goes out from the serverBrowse the office's internal admin pages from home, as if you were in the office

Pick a kind and fill in the ports. The builder writes the command and shows the path:

ssh -N -L 5433:10.10.2.5:5432 kade-api
  1. Your appconnects to localhost:5433
  2. SSH (encrypted)laptop → kade-api:22
  3. kade-apiopens TCP to 10.10.2.5:5432
  4. 10.10.2.5port 5432

Anything that connects to localhost:5433 on your laptop reaches 10.10.2.5:5432, which only kade-api can see. The part from kade-api to 10.10.2.5 is a normal connection inside the VPC, not SSH-encrypted.

Jump hosts and bastions

A bastion (jump host) is one hardened machine you SSH into first, to reach others that have no public access. ProxyJump (ssh -J) does it cleanly: your laptop opens an SSH connection through the bastion to the target, so the end-to-end encryption and your private key stay on your laptop:

ssh -J thirana@kade-api thirana@10.10.2.5     # or just: ssh kade-db, with the config above

The bastion only sees an encrypted stream. This is why ProxyJump is safer than logging in to the bastion and running ssh again from there.

SSH in GCP: OS Login and IAP

Opening port 22 to 0.0.0.0/0 invites constant login attempts from bots. GCP offers a better way in:

Your laptopgcloud compute sshIdentity-Aware Proxy (IAP)checks your Google loginand your IAM rolekade-vpc · no external IPskade-db10.10.2.5 : 22HTTPS (443)from 35.235.240.0/20firewall: allow tcp:22only from 35.235.240.0/20(IAP's range)

Wide by design - scroll it sideways.

IAP TCP forwardingYour SSH travels inside HTTPS to Google's Identity-Aware Proxy, which checks who you are and whether IAM allows you, then connects to the VM's internal IP. The VM needs no external IP, and port 22 is open only to IAP's address range.
OS LoginLinux accounts and SSH access come from IAM instead of keys scattered in VM metadata. Remove someone from the IAM role and their access ends everywhere. It can require 2-step verification.
Tunnels tooThe same IAP path can forward any TCP port, e.g. kade-db's PostgreSQL to your laptop, with no SSH involved at all (commands below).
gcloud compute ssh kade-db --zone=asia-southeast1-b --tunnel-through-iapgcloud compute start-iap-tunnel kade-db 5432 --local-host-port=localhost:5433 --zone=asia-southeast1-bpsql -h localhost -p 5433 -U kade    # in another terminal

Hardening SSH

#Setting or habitWhy
1PasswordAuthentication noKeys only: nothing for bots to guess
2PermitRootLogin noLog in as yourself, then use sudo: every action is tied to a person
3No public port 22 (use IAP or a VPN)The best attack surface is none
4If 22 must be public: allow only known source IPse.g. only the office's 198.51.100.20/32 (a /32, chapter 3)
5Passphrase-protected or hardware keys; OS Login with 2-step verificationA stolen laptop file is not enough
6Keep OpenSSH updated; review who has access regularlyOld keys of people who left are a common hole

Troubleshooting

ssh -v kade-api prints every step of section 3; -vvv prints even more. Common errors:

#ErrorMeaningCheck
1Connection timed outSYNs dropped (chapter 16)Firewall rule for 22; for IAP, the 35.235.240.0/20 rule
2Connection refusedRST: nothing listening on 22Is sshd running?
3Permission denied (publickey)The server did not accept any key offeredRight user? Public key in authorized_keys? File permissions on the server (~/.ssh 700, authorized_keys 600)? OS Login role?
4Host key verification failedHost key changed (section 4)Rebuilt VM, or an attack. Confirm, then ssh-keygen -R
5Too many authentication failuresYour agent offered too many keys before the right oneIdentitiesOnly yes + IdentityFile in the config
6client_loop: send disconnect: Broken pipe after idleA NAT or firewall forgot the idle connection (chapter 21)ServerAliveInterval 30

Summary

#IdeaIn one lineNew terms
1-2SSHEncrypted remote access on TCP 22; transport, user auth, connection layersSSH, channel
3ConnectingVersion, KEXINIT, ECDH key exchange, host key signature, user auth, channelKEXINIT, session ID
4Host keysTrust on first use; known_hosts; a changed key means attack or rebuildhost key, TOFU, known_hosts
5-6User keysSign the session ID with your private key; ed25519; agent; configauthorized_keys, ssh-agent
8Tunnels-L local, -R remote, -D SOCKSport forwarding, SOCKS
9Jump hostsProxyJump through a bastion, end-to-end encryptedbastion, ProxyJump
10GCPIAP TCP forwarding and OS Login: no public 22, IAM-based accessIAP, OS Login
11-12PracticeKeys only, no root, no public port; ssh -v and the common errors

Try it yourself

Every step of a real connection

  • What to look for: kex: algorithm: curve25519-sha256, Server host key: ssh-ed25519, Authenticated to github.com.
  • From section: 3. Connecting, step by step
ssh -v git@github.com

A server's host key fingerprint

ssh-keyscan -t ed25519 github.com | ssh-keygen -lf -

A new key, and the keys in your agent

  • Steps: ssh-keygen -t ed25519, then ssh-add -l
  • What to look for: The fingerprint of the key you just made.
  • From section: 6. Managing keys and config
ssh-keygen -t ed25519ssh-add -l

A local tunnel (-N: no shell)

ssh -N -L 5433:10.10.2.5:5432 kade-api

A SOCKS proxy

  • What to look for: Set the browser's SOCKS proxy to localhost:1080; check your IP at ifconfig.me.
  • From section: 8. Tunnels: port forwarding
ssh -N -D 1080 kade-api

SSH with no external IP

gcloud compute ssh kade-db --tunnel-through-iap --zone=asia-southeast1-b

The SSH server's effective settings

  • What to look for: passwordauthentication no, permitrootlogin no.
  • Runs on: on the server
  • From section: 12. Troubleshooting
sudo sshd -T | grep -Ei 'passwordauth|permitroot'

Spotted a mistake, or something unclear? Suggest an edit on GitHub