Logging in

How do you get a shell on a machine in another building?

your computerterminal and sshencrypted, TCP port 22web01sshd starts your shellssh ana@web01anathe account on the serverweb01its name or IP addressProve who you are with a password✗typed at every login✗can be guessed by anyone who can reach port 22✗no use to a script that runs unattendedProve who you are with a key✓a file on your computer; nothing to type✓far too long to guess, and never sent✓works for scripts, backups and deploysSSH gives you a shell on another machine over an encrypted connection. Keys are how you log in to it.Before you prove who you are, the server proves who it is, which is the question ssh asks the first time you connect;the next page is about answering it properly. Then come key pairs, a config file that shortens the commands,copying files over the same connection, and locking the server down.

ssh user@host opens an encrypted connection to sshd on port 22 and starts a shell there; a key pair replaces the password.

Known hosts

Trust the server’s key once, and ssh checks it every time after

$ ssh web01The authenticity of host 'web01 (192.168.10.21)' can't be established.ED25519 key fingerprint is SHA256:fDaSgzSuuFzrPsja41mn5T7Oa+ZTrTxUAHm2+DVq5Lw.1This key is not known by any other names.Are you sure you want to continue connecting (yes/no/[fingerprint])? yesWarning: Permanently added 'web01' (ED25519) to the list of known hosts.21Compare with the server’s own fingerprint, from its console:ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub2Saved in ~/.ssh/known_hosts and checkedsilently at every later connectionWARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!the key differs from the saved one: a rebuilt server, or someone in the middle.Check the new fingerprint, then ssh-keygen -R web01 removes the old line.The first connection asks you to trust the server’s key; every later one checks it hasn’t changed.Typing yes without checking is how a fake server gets trusted, so compare the fingerprint the first time. After that, ssh refuses toconnect if the key changes. Large fleets publish host keys centrally (DNS SSHFP records or an SSH certificate authority).

At the first connection you accept the server’s host key into known_hosts; if it ever changes, ssh refuses and warns you.

Key pairs

The private key stays with you; the public key goes everywhere

your laptop: ~/.ssh/id_ed25519private key, mode 600, never leavesid_ed25519.pubpublic key: safe to give anyonessh-copy-id web01web01: /home/ana/.ssh/authorized_keysone public key per line; mode 600the .ssh directory: mode 700ssh-ed25519 AAAAC3Nz…QMdI ana@laptoptype, the key, a comment$ ssh-keygen -t ed25519 -C ana@laptopThe key fingerprint is:SHA256:Nb11plxEHscaOeeVLHyFBCX4zA4CcyMbKYsiwq2DdTQ ana@laptopa passphrase encrypts the private key on disk;ssh-agent remembers it for the sessionA key pair splits the secret: the private half stays with you, the public half goes on every server.Anyone can hold your public key; only the private key can produce a signature that matches it. ssh-copy-id appends the public keyto authorized_keys on the server, using your password one last time. Ed25519 keys are short and fast; RSA keys need 3072 bits or more.

A key pair: the private key stays on your machine, the public key goes into authorized_keys on each server.

TLS certificates · Going deeper · 1 of 3

A public key with a name, dates and a trusted signature

root CAin the trust storesignsintermediate CAsent by the serversignsweb01.labthe server certificateweb01.keyprivate, mode 600web01.crtpublic, the server sends it$ openssl req -new -newkey rsa:2048 -nodes -keyout web01.key -out web01.csr -subj "/CN=web01.lab"a request to send to a CA; or -x509 -days 365 instead of -new for a self-signed test certificate$ openssl x509 -in web01.crt -noout -subject -issuer -datessubject=CN = web01.labissuer=CN = web01.labnotBefore=Nov 15 10:23:44 2026 GMTnotAfter=Nov 15 10:23:44 2027 GMTself-signed: subject and issuer are the samenotAfter: when it expiresopenssl s_client -connect web01:443shows the chain a live server sendsTLS works like SSH keys plus a signature from someone both sides trust.A certificate is a public key with a name and dates, signed by a certificate authority. Clients trust it if the chain leads to a root intheir store (update-ca-trust on RHEL, update-ca-certificates on Ubuntu add your own). Expired certificates are a classic outage: watch notAfter.

A certificate binds a public key to a name and is signed by a certificate authority the client trusts.

Key pairs · Going deeper · 2 of 3

Six steps: agree a key, check the server, then prove who you are

clientweb011TCP to port 22, then both send their versionsSSH-2.0-OpenSSH_9.6p12Key exchange: both compute the same session keynothing secret crosses; all that follows is encrypted3The server signs with its host keyyou check it against known_hosts: is this really web01?4You offer your public keythe server finds it in authorized_keys5You sign this session’s data with your private keythe server checks the signature with the public key6Authenticated: a shell opens over the encrypted channelno password was sent, and none could be stolenSSH agrees a secret key first, proves the server’s identity, then proves yours with a signature.Your private key never leaves the laptop: it signs data unique to this session, and the server checks the signature with the publickey it already holds. A stolen recording of the session is useless, and a fake server cannot pass step 3. ssh -v prints each step.

SSH runs a key exchange, checks the server’s host key, then you prove your identity by signing with your private key.

ssh -v · Going deeper · 3 of 3

The same six steps, printed by ssh -v

$ ssh -v web01 2>&1 | grep debug1 (trimmed)debug1: Local version string SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.201debug1: kex: algorithm: sntrup761x25519-sha512@openssh.com2debug1: kex: host key algorithm: ssh-ed255192debug1: Server host key: ssh-ed25519 SHA256:fDaSgzSuuFzrPsja41mn5T7Oa+ZTrTxUAHm2+DVq5Lw3debug1: Authentications that can continue: publickey4debug1: Offering public key: /home/ana/.ssh/id_ed25519 ED25519 SHA256:Nb11plxEHsca…4debug1: Server accepts key: /home/ana/.ssh/id_ed25519 ED25519 SHA256:Nb11plxEHsca…5debug1: Authenticated to web01 ([192.168.10.21]:22) using "publickey".6The numbers match the handshake steps. sntrup761x25519 mixes a post-quantum algorithm with X25519; newer OpenSSH uses mlkem768x25519.When a login fails, ssh -v shows the step it stopped at; the server’s side is in its journal.Stopped before the host key: network or firewall. Host key rejected: known_hosts. Key offered but not accepted: authorized_keys,its permissions, or the wrong user. On the server, journalctl -u sshd (ssh on Ubuntu) says why it refused, for example"Authentication refused: bad ownership or modes for directory /home/ana/.ssh". -vvv gives even more.

ssh -v prints each handshake step, so you can see where a failing login stops.

Client config

One config file turns long commands into short names

~/.ssh/configHost web011 HostName 192.168.10.21 User ana Port 22222 IdentityFile ~/.ssh/id_ed25519Host db01 ProxyJump bastion3Host *4 ServerAliveInterval 60Before$ ssh -p 2222 -i ~/.ssh/id_ed25519 \ ana@192.168.10.21After$ ssh web01scp, rsync and git use it too1A short namethe first match for each setting wins2ProxyJumpreach db01 through the bastion host3Host *: defaultsso put it lastA config file turns long ssh commands into short names, and the agent asks for your passphrase once.ssh reads ~/.ssh/config (then /etc/ssh/ssh_config) and uses the first value it finds for each option. With a passphrase on the key,eval "$(ssh-agent)"; ssh-add unlocks it once per session. The file must not be writable by others, or ssh ignores it.

~/.ssh/config stores the address, user, port, key and jump host per name; ssh-agent holds your unlocked key.

Copying files

rsync sends only what changed; scp sends everything

first run$ rsync -av site/ web01:site/sending incremental file listcreated directory site./about.htmlindex.htmlcss/css/site.csssent 8,403 bytes received 111 bytes1one file changed$ rsync -av site/ web01:site/sending incremental file listabout.htmlsent 814 bytes received 60 bytes2scp copies everything, every time$ scp report.pdf web01:/tmp/$ scp -r web01:/etc/nginx .rsync sends only what changed-a keeps owners, modes, times, links--delete removes files gone from the source-n shows what would happen, does nothingThe trailing slash matters:site/ the contents of sitesite the folder itself, as site/sitesftp web01 gives an interactive session.scp copies whole files; rsync compares both sides and sends only the differences.Both run over SSH, so they use your keys and your config. The second run above sent 814 bytes instead of 8,403: only about.htmlchanged. For backups and deployments use rsync, and try it with -n first, especially with --delete.

scp copies whole files; rsync compares both sides and sends only differences, over the same SSH connection.

Copying files · Going deeper

Carry another connection inside SSH, through the firewall

Local forward: reach a private database from your laptop$ ssh -L 5433:db01:5432 web01localhost:5433inside the SSH connectionweb01plain, inside the networkdb01:5432psql -h localhost -p 5433reaches db01, which only web01 canRemote forward: let a server reach something on your side$ ssh -R 8080:localhost:3000 web01web01:8080 now leads to port 3000 on your laptop$ ssh -D 1080 web01dynamic: a SOCKS proxy; the browser goes out through web01An SSH tunnel carries another connection inside the encrypted one, through firewalls that allow only SSH.-L opens a port on your machine that leads to a host and port as seen from the server. -R does the reverse. Add -N to forward withouta shell, and -f to go to the background. Servers can forbid tunnels with AllowTcpForwarding no.

A local forward (-L) opens a port on your machine that leads, through the server, to a host only it can reach.

Hardening

No root, no passwords, and only the people you name

/etc/ssh/sshd_config.d/50-hardening.confPermitRootLogin no1PasswordAuthentication no2AllowGroups sshusers3MaxAuthTries 3X11Forwarding no1No direct root loginslog in as yourself, then sudo2Keys onlypassword guessing becomes useless3Only listed peopleeveryone else is refusedApply it safely# sshd -t && systemctl reload sshdtest the syntax first; on Ubuntu the unit is sshKeep your current session open and log in from a second terminal before you close it.A new port also needs SELinux and the firewall told:# semanage port -a -t ssh_port_t -p tcp 2222; firewall-cmd --permanent --add-port=2222/tcp; firewall-cmd --reloadHarden SSH by refusing root and passwords, and by naming who may log in.Drop-in files in sshd_config.d are read before the main file, and the first value read wins, so a drop-in beats the defaults. Check theresult with sshd -T | grep -i passwordauth. Only turn passwords off once your key login works, from a second terminal.

Set PermitRootLogin no, PasswordAuthentication no and AllowGroups in a drop-in; test with sshd -t before reloading.

Lab

Key login, file copies, a tunnel and a hardened server

$ ssh-keygen -t ed25519 -C ana@laptop1$ ssh-copy-id ana@web012Number of key(s) added: 1$ ssh web01 hostname3web01.lab$ rsync -av site/ web01:site/ | tail -24sent 814 bytes received 60 bytes 1,748.00 bytes/sectotal size is 8,114 speedup is 9.28# sshd -t && systemctl reload sshd5$ ssh -o PubkeyAuthentication=no web016ana@web01: Permission denied (publickey).1Make a keywith a passphrase2Install iton the server3Log in by namethrough ~/.ssh/config4Sync filesonly changes travel5Harden sshdtest, then reload6Prove passwords are offa refusal is successLab: set up key login to a server, use it to copy and tunnel, then shut the door on passwords.You need two machines (two VMs, or your laptop and a VM). Press the down arrow for the steps.

Generate and install a key, name the server in your config, copy with scp and rsync, tunnel a port, then turn off password and root logins.

Lab · Going deeper

Key login, file copies, a tunnel and a hardened server

Use two machines: a client (your laptop or a VM) and a server VM you can also reach by console. Keep the console open until the last step works.

Steps

  1. Make a key. ssh-keygen -t ed25519 -C "<you>@<machine>" and give it a passphrase. ls -l ~/.ssh: the private key must be -rw-------.
  2. Install it. ssh-copy-id <user>@<server>. On the server, check ~/.ssh is 700 and authorized_keys 600, owned by you.
  3. Check the host key. On the server console: ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub. Compare it with what the client saw at first login.
  4. Name it. Write a Host entry in ~/.ssh/config so that ssh <name> works. Add the key to the agent: eval "$(ssh-agent)"; ssh-add.
  5. Copy. scp a file each way. rsync -av a folder, change one file, rsync again, and compare the bytes sent. Try --delete with -n first.
  6. Tunnel. On the server, run python3 -m http.server 8000 --bind 127.0.0.1. From the client: ssh -N -L 8001:localhost:8000 <name>, then curl localhost:8001.
  7. Harden. Create /etc/ssh/sshd_config.d/50-hardening.conf with PermitRootLogin no and PasswordAuthentication no. sshd -t; systemctl reload sshd (ssh on Ubuntu).
  8. Prove it. From a second terminal: ssh <name> works; ssh -o PubkeyAuthentication=no <name> is refused; ssh root@<server> is refused. journalctl -u sshd shows both refusals.
  9. Make a certificate. openssl req -x509 -newkey rsa:2048 -nodes -days 30 -keyout web.key -out web.crt -subj "/CN=<server>"; openssl x509 -in web.crt -noout -dates.
Check: ssh <name> logs in without a password prompt (the agent holds the passphrase), the tunnelled curl returns a directory listing, and password and root logins are both refused.

Lesson complete

You finished “SSH and remote work”

Nicely done.

Open in a new tab