Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

LX
Linux
0/11 completed
Beginner
The Linux file systemUsers, groups and permissionsPackage managers
Intermediate
Processes and signalsDisks, storage and archivesNetworking commandsSSH and remote access
Advanced
systemd and servicesLogs and troubleshooting
Pro
Securing a serverPerformance and resource limits
Tracks / Linux / Pro

Securing a server

A new server on the internet gets its first login attempts from bots within minutes. They scan every address for SSH with weak passwords, outdated software and open databases. You don't need to be a security expert to stop almost all of it: a short, boring checklist done every time does the job. This lesson is that checklist, plus how to check your work.

The checklist

# Step Why
1 Install updates and turn on automatic security updates Most break-ins use known, already-fixed bugs
2 Create a normal user with sudo; log in with SSH keys Passwords get guessed
3 Disable SSH password and root logins Removes the bots' main target
4 Firewall: allow only the ports you need Nothing else is reachable
5 Run each service as its own unprivileged user A hacked app can't take over the machine
6 Keep databases on 127.0.0.1 or a private network Open databases are found and wiped in hours
7 Protect secrets: 600 files, environment, a secret manager Leaked keys are the other big cause of breaches
8 Ban repeated failed logins (fail2ban) Slows down guessing, cleans up logs
9 Watch logs and set up backups (and test restoring them!) You'll notice problems, and can recover

Steps 2 and 3 are in the SSH lesson, step 4 in Networking commands, and step 5 in systemd and services. Here's the rest.

1. Updates

bash
sudo apt-get update > /dev/null 2>&1
apt list --upgradable 2>/dev/null | tail -n +2 | wc -l
Output
2

That's how many packages have updates waiting. Install them with sudo apt upgrade, and have security updates installed every day automatically:

bash
sudo apt install unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades   # answer "Yes"
cat /etc/apt/apt.conf.d/20auto-upgrades

Its log is in /var/log/unattended-upgrades/. Some updates (the kernel, libc) only take effect after a reboot; check for /var/run/reboot-required and plan one.

3. Check what SSH really allows

The SSH lesson showed how to set PasswordAuthentication no and PermitRootLogin no. Always check the effective settings, because a later file in sshd_config.d/ (some cloud images add one) can override yours:

bash
systemctl start ssh
printf 'PasswordAuthentication no\nPermitRootLogin no\n' > /etc/ssh/sshd_config.d/50-hardening.conf
printf 'PasswordAuthentication yes\n' > /etc/ssh/sshd_config.d/10-cloud-init.conf
sshd -T | grep -E "^(passwordauthentication|permitrootlogin) "
ls /etc/ssh/sshd_config.d/
Output
permitrootlogin no
passwordauthentication yes
10-cloud-init.conf  50-hardening.conf

Surprised? For SSH, the first value read wins, and files are read in alphabetical order: 10-cloud-init.conf beat 50-hardening.conf. That's exactly the kind of thing sshd -T catches. Fix it by removing the other file or naming yours 01-hardening.conf:

bash
mv /etc/ssh/sshd_config.d/50-hardening.conf /etc/ssh/sshd_config.d/01-hardening.conf
sshd -T | grep -E "^(passwordauthentication|permitrootlogin) "
sshd -t && systemctl reload ssh && echo "reloaded"
Output
permitrootlogin no
passwordauthentication no
reloaded

6. Find everything that listens

Anything listening on 0.0.0.0 (or [::]) is reachable from outside unless the firewall blocks it. Check regularly:

bash
apt-get install -y -qq redis-server > /dev/null 2>&1; systemctl start redis-server nginx
ss -tlnp | awk 'NR > 1 { split($6, p, "\""); print $4, p[2] }' | sort -u | column -t
Output
0.0.0.0:22      sshd
0.0.0.0:80      nginx
127.0.0.1:6379  redis-server
[::1]:6379      redis-server
[::]:22         sshd
[::]:80         nginx

Redis is on 127.0.0.1 only, as it should be. nginx and SSH face the world, which is intended. Anything else you don't recognise: find out what it is, then stop it, bind it to 127.0.0.1, or firewall it.

7. Secrets and file permissions

bash
mkdir -p /etc/shop
printf 'DATABASE_URL=postgres://shop:s3cret@localhost/shop\n' > /etc/shop/shop.env
chown root:shop /etc/shop/shop.env 2>/dev/null || chown root:root /etc/shop/shop.env
chmod 640 /etc/shop/shop.env
ls -l /etc/shop/shop.env | awk '{ print $1, $3, $4, $NF }'
echo "--- world-writable files outside /proc, /sys and /tmp (should be none):"
find / -xdev -type f -perm -0002 -not -path "/proc/*" -not -path "/sys/*" -not -path "/tmp/*" 2>/dev/null | head -5
echo "--- setuid programs:"
find /usr/bin /usr/sbin -perm -4000 -type f | wc -l
Output
-rw-r----- root root /etc/shop/shop.env
--- world-writable files outside /proc, /sys and /tmp (should be none):
--- setuid programs:
9
  • Keep secrets in a file readable only by root and the service's group (640), loaded with EnvironmentFile= in the unit. Never in the code, the Git repository, or the unit file itself (systemctl show prints those to anyone).
  • World-writable files let any user change them. There should be none outside temp folders.
  • Learn your system's normal setuid list; a new one appearing is a red flag.

8. fail2ban

fail2ban watches logs for repeated failures and blocks those IPs in the firewall for a while:

bash
sudo apt install fail2ban
sudo tee /etc/fail2ban/jail.local <<'EOF'
[sshd]
enabled  = true
maxretry = 5
findtime = 10m
bantime  = 1h
EOF
sudo systemctl restart fail2ban
sudo fail2ban-client status sshd      # who's banned right now

With password logins disabled, bots can't get in anyway, but fail2ban keeps the noise down and protects other services too (nginx, Postfix…).

9. Who's been here?

bash
useradd -m -s /bin/bash olduser 2>/dev/null; echo "olduser:x" | chpasswd
echo "--- accounts with a login shell:"
grep -vE "nologin|false|sync$" /etc/passwd | cut -d: -f1
echo "--- accounts that have a password set:"
awk -F: '$2 !~ /^[!*]/ { print $1 }' /etc/shadow
echo "--- members of the sudo group:"
getent group sudo | cut -d: -f4
passwd -l olduser > /dev/null && echo "locked olduser"
Output
--- accounts with a login shell:
root
ubuntu
you
olduser
--- accounts that have a password set:
olduser
--- members of the sudo group:
ubuntu
locked olduser

Review this list now and then: remove people who left (userdel -r), and lock accounts you're not sure about (passwd -l). last shows recent logins, lastb failed ones, and journalctl -u ssh every SSH connection.

A quick self-audit

Lynis is a free tool that checks hundreds of these settings and suggests improvements:

bash
sudo apt install lynis
sudo lynis audit system --quick     # read the "Suggestions" section at the end

Other good habits:

  • Put a reverse proxy in front of apps. nginx or Caddy handles HTTPS (free certificates from Let's Encrypt), limits request sizes and hides the app server.
  • Back up, off the server, and practise restoring. Ransomware and rm -rf mistakes are only survivable with backups you can actually restore.
  • Fewer things = fewer holes. Remove packages and services you don't use.
  • Rebuild instead of repair. If you think a server was compromised, don't try to clean it: build a fresh one from a known-good image and rotate every secret it held.

Practice

  1. On a test server, go through the checklist from top to bottom.
  2. Run sudo sshd -T and check that password and root logins are really off.
  3. List every listening port and explain what each one is.
  4. Find all files in /etc that aren't owned by root: find /etc ! -user root.
✎ Check your understanding

1.What's the most common way servers get broken into?

2.Why check settings with sshd -T instead of reading sshd_config?

3.A Redis server listens on 0.0.0.0:6379 with no firewall. What's the risk?

4.Where should a service's database password live?

← Logs and troubleshooting