SSH Keys & Remote Access
A new deploy account has been created on the shop's server and the CI pipeline needs to log in to it with a key, never a password. Someone already tried to set it up and gave up because "the key doesn't work". You will set up key login properly, make connecting effortless and then lock the SSH server down.
- Explain how public and private keys work and create an ed25519 key pair
- Authorize a key for a user and fix the permission problems that make sshd ignore it
- Use ~/.ssh/config host aliases, run remote commands and copy files with scp
- Harden sshd: no root login, no passwords, test the config and reload safely
SSH (Secure Shell) is how we log in to Linux servers, run commands on them and copy files, over an encrypted connection. It is also how Ansible manages servers, how Git talks to GitHub with [email protected]:... and how CI pipelines deploy.
Key-based login uses a pair of keys:
| Key | File | Who has it |
|---|---|---|
| Private key | ~/.ssh/id_ed25519 | Only you. Never share or copy it to a server. |
| Public key | ~/.ssh/id_ed25519.pub | Goes to every server you want to log in to, in ~/.ssh/authorized_keys |
When you connect, the server sends a challenge that only the matching private key can answer. The private key never leaves your machine, and there is no password to guess or steal. That's why production servers usually allow keys only.
In this lab the "server" is the same machine: you connect to localhost as the user deploy. Everything works the same against a real remote server.
- Press Start lab. You get your own Ubuntu machine on the right, just for you.
- Read each step. Commands with a ▶ Run button can be sent to the terminal in one click, but typing them yourself helps you remember.
- Do the Your task part, then press Check my work. The check looks at the machine and tells you what is right or still missing.
- Stuck? Open the hint. Nothing you do here can break anything real.
Create a key pair
Generate an ed25519 SSH key pair for root.
Why we do this: a key pair is your identity on every server, on GitHub and in your CI system. Choosing a modern key type and protecting the private key properly is the foundation of everything else in this lab.
1. Check for existing keys
ls -la ~/.sshNever overwrite a key that is already in use. Here there is none yet.
2. Generate an ed25519 key
ssh-keygen -t ed25519 -C "root@shop-lab"| Option | Meaning |
|---|---|
-t ed25519 | the key type: modern, short and fast. Use it unless something old forces RSA (-t rsa -b 4096). |
-C | a comment to recognise the key, often your email |
-f FILE | where to save it (default ~/.ssh/id_ed25519) |
-N '' | the passphrase (empty here) |
Press Enter to accept the default file. When it asks for a passphrase, press Enter twice to leave it empty for this lab.
In real life, protect your personal key with a passphrase and use
ssh-agentso you only type it once per session. Keys used by automation (CI) usually have no passphrase, which is why they are stored as protected secrets.
3. Look at what you created
ls -l ~/.ssh
cat ~/.ssh/id_ed25519.pub
ssh-keygen -lf ~/.ssh/id_ed25519.pubThe public key is a single line: type, key, comment. ssh-keygen -l shows its fingerprint, a short form for comparing keys. Notice the permissions: the private key is -rw------- (600). SSH refuses to use a private key that others can read.
Create an ed25519 key pair for root at ~/.ssh/id_ed25519, without a passphrase.
Expected result: ls -l ~/.ssh shows id_ed25519 (mode 600) and id_ed25519.pub.
Hint: the commands, explained
ssh-keygen -t ed25519 -C "root@shop-lab" -f ~/.ssh/id_ed25519 -N ''What each part does
ssh-keygen: create a key pair.-t ed25519the modern, short, fast key type.-C "root@shop-lab": a comment saved in the public key, so you can tell keys apart later.-f ~/.ssh/id_ed25519: where to write it. You get two files:id_ed25519(private, never share it) andid_ed25519.pub(public, safe to copy to servers).-N '': an empty passphrase so the lab doesn't stop to ask. On your own laptop, set one.
Log in with your key
Authorize your key for the deploy user and log in without a password.
Why we do this: "Permission denied (publickey)" is one of the most searched SSH errors. Most of the time the key is fine and the problem is file permissions on the server: sshd silently ignores authorized_keys if anyone else could have changed it.
1. Install your public key for deploy
On a real server you would usually run ssh-copy-id deploy@server, which logs in once with a password and appends your key. Here we do what it does by hand, because that's how you learn to debug it:
cat ~/.ssh/id_ed25519.pub >> /home/deploy/.ssh/authorized_keysUse >> so you don't remove keys that are already there. Now try to log in:
ssh deploy@localhostThe first time, SSH shows the server's host key fingerprint and asks whether to trust it. Type yes. It is saved in ~/.ssh/known_hosts, and SSH will warn you loudly if it ever changes. Then... it asks for a password. The key was ignored. Press Ctrl+C.
2. Find out why
ssh -v deploy@localhost-v shows each step. You will see your key being offered but not accepted. The server side explains it (Authentication refused: bad ownership or modes). Look at the files:
ls -ld /home/deploy /home/deploy/.ssh /home/deploy/.ssh/authorized_keys3. The rules sshd enforces (StrictModes)
| Path | Owner | Mode |
|---|---|---|
/home/deploy | deploy | not writable by group or others (e.g. 755) |
~/.ssh | deploy | 700 |
~/.ssh/authorized_keys | deploy | 600 |
Fix them:
chown -R deploy:deploy /home/deploy/.ssh
chmod 700 /home/deploy/.ssh
chmod 600 /home/deploy/.ssh/authorized_keys4. Try again
ssh deploy@localhost
whoami
exitNo password this time. You are logged in as deploy with your key.
Make key login work: root must be able to log in as deploy@localhost with the key from step 1, with no password.
Expected result: ssh deploy@localhost whoami prints deploy without asking for a password.
Hint: the commands, explained
cat ~/.ssh/id_ed25519.pub >> /home/deploy/.ssh/authorized_keys
chown -R deploy:deploy /home/deploy/.ssh
chmod 700 /home/deploy/.ssh && chmod 600 /home/deploy/.ssh/authorized_keysWhat each part does
cat KEY.pub >> /home/deploy/.ssh/authorized_keys: append your public key to deploy's list of keys allowed to log in. (ssh-copy-iddoes this step for you over the network.)chown -R deploy:deploy: the folder and file must belong to deploy.chmod 700folder,600file: sshd ignores keys if others can write to these, so it can't be tricked into trusting a key someone else planted.
SSH config, remote commands and scp
Connect with a short host alias and copy the release notes to the server.
Why we do this: with dozens of servers, typing ssh -i ~/.ssh/key -p 2222 [email protected] gets old fast and invites mistakes. ~/.ssh/config gives each server a short name. Running remote commands and copying files are what deployment scripts and Ansible do all day.
1. Create a host alias
nano ~/.ssh/configHost shop
HostName localhost
User deploy
Port 22
IdentityFile ~/.ssh/id_ed25519Save, then protect it and try it:
chmod 600 ~/.ssh/config
ssh shop
exitssh -G shop prints the final settings SSH will use, handy for debugging a config. Host * blocks apply to every host, and the first value found for each setting wins, so put specific hosts first.
2. Run a command without logging in
ssh shop 'hostname; uptime; df -h /'
ssh shop 'ls -la ~'The command runs on the server and its output comes back to you. Quote it, or your local shell will expand things like ~ and * before SSH sees them.
3. Copy files with scp
scp /root/release-notes.txt shop:~/
ssh shop 'cat ~/release-notes.txt'
scp shop:~/release-notes.txt /tmp/copy-back.txtscp SOURCE DEST, where a remote path is written host:path. Add -r to copy folders. For big or repeated copies, rsync -avz folder/ shop:~/folder/ only sends what changed.
Port forwarding is the other SSH superpower:
ssh -L 5432:db.internal:5432 bastionmakes a private database reachable on your laptop's port 5432 through a bastion host.
- Add a host alias
shopto~/.ssh/configthat connects tolocalhostasdeploywith your key. - Use it with
scpto copy/root/release-notes.txtinto deploy's home folder.
Expected result: ssh shop whoami prints deploy, and ssh shop cat release-notes.txt shows the release notes.
Hint: the commands, explained
printf 'Host shop\n HostName localhost\n User deploy\n IdentityFile ~/.ssh/id_ed25519\n' >> ~/.ssh/config
chmod 600 ~/.ssh/config
scp /root/release-notes.txt shop:~/What each part does
printf ... >> ~/.ssh/config: add a shortcut calledshop.HostNamethe real address,Userwho to log in as,IdentityFilewhich private key to use.chmod 600: ssh refuses a config file that others can write to.scp FILE shop:~/: copy a file over SSH to theshophost's home folder. The config fills in the user, address and key.
Harden the SSH server
Disable root login and password authentication without locking yourself out.
Why we do this: any server with SSH open to the internet sees password-guessing bots within minutes. Allowing keys only and blocking direct root login removes the two easiest ways in. It is on every server hardening checklist and a favourite interview question.
1. See the current settings
sshd -T | grep -E '^(permitrootlogin|passwordauthentication|pubkeyauthentication|port) 'sshd -T prints the effective configuration after reading every file. It is more reliable than reading the config by eye.
2. Use a drop-in file
The main file /etc/ssh/sshd_config includes everything in /etc/ssh/sshd_config.d/*.conf first, and for most settings the first value sshd reads wins. Putting your changes in their own file keeps them safe from package upgrades and easy to review:
nano /etc/ssh/sshd_config.d/10-hardening.confPermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yesOther common hardening settings are MaxAuthTries 3, AllowUsers deploy (only these users may log in) and moving Port away from 22 to cut down log noise.
3. Test before you reload
sshd -t && echo "config OK"sshd -t checks the configuration for errors. Always run it first: a broken config means sshd won't start again, and on a remote server that can lock everyone out.
4. Reload safely
On a normal server you would run systemctl reload ssh (sshd on Red Hat). Here sshd runs without systemd, so send it the reload signal directly:
kill -HUP $(cat /run/sshd.pid)Reloading keeps existing connections open. The golden rule on a real server: keep your current session open and test in a second terminal that you can still log in before you disconnect.
ssh shop whoamiConfigure the SSH server so that root cannot log in and password authentication is disabled, check the config with sshd -t, reload sshd, and confirm that ssh shop still works.
Expected result: sshd -T shows permitrootlogin no and passwordauthentication no, and ssh shop whoami still prints deploy.
Hint: the commands, explained
printf 'PermitRootLogin no\nPasswordAuthentication no\n' > /etc/ssh/sshd_config.d/10-hardening.conf
sshd -t && kill -HUP $(cat /run/sshd.pid)What each part does
- Files in
/etc/ssh/sshd_config.d/are read by the SSH server, and they're safer than editing the main file. PermitRootLogin no: nobody can log in directly as root.PasswordAuthentication no: only keys work, so password guessing is useless.sshd -t: test the config for errors.&&: only if the test passes,kill -HUPmakes the running sshd reload it. Your current session stays connected.
Brilliant work!
You set up passwordless key login for a deploy account, fixed the permission problem that defeated the last person, made connecting effortless and hardened the SSH server without locking yourself out.
Interview-ready takeaways:
ssh-keygen -t ed25519creates the pair. The private key stays with you (mode 600); the public key goes into the server's~/.ssh/authorized_keys(ssh-copy-iddoes this for you).- "Permission denied (publickey)": run
ssh -v, then check ownership and modes: home not group-writable,~/.ssh700,authorized_keys600, all owned by the user. known_hostsprotects you from talking to the wrong server; a changed host key is a warning to take seriously.~/.ssh/confighost aliases,ssh host 'command',scp/rsyncandssh -Lport forwarding cover most daily work.- Harden with
PermitRootLogin noandPasswordAuthentication noin/etc/ssh/sshd_config.d/, check withsshd -tandsshd -T, reload, and test from a second session before you log out.
Next: the Shell Scripting: From Commands to Automation lab.
Create an SSH key pair, log in without a password, debug the permission errors that break key login, use ~/.ssh/config and scp, and harden the SSH server.
A new deploy account has been created on the shop's server and the CI pipeline needs to log in to it with a key, never a password. Someone already tried to set it up and gave up because "the key doesn't work". You will set up key login properly, make connecting effortless and then lock the SSH server down.