In one minute
- Hardening means making a server harder to attack: fewer services, fewer accounts, tighter permissions, quick updates and a record of who did what.
- A brand-new server is not secure by default. Security teams, auditors and standards such as the CIS Benchmarks expect DevOps engineers to build security into every server image and pipeline.
- You close every door you do not need, lock the ones you keep, and put cameras on them. Then you write it all as code, so every server gets the same protection automatically.
- 👉 Building a new server image, preparing for a security audit, and after a security scan finds problems.
Think of it like: securing a house. Lock the windows you never open (unused ports), give out as few keys as possible (accounts), fix broken locks quickly (patches), and install cameras (audit logs).
The principles
| Principle | What it means | In practice |
|---|---|---|
| Least privilege | Give only the access that is needed | Services run as their own users; people get only the sudo they need |
| Small attack surface | Less to attack | Remove unused packages; close unused ports |
| Defence in depth | Several layers of protection | Security group and server firewall and app login |
| Patch quickly | Fix known holes fast | Automatic security updates; rebuild images often |
| Audit everything | Record who did what | Logs of logins, sudo and changes, sent off the server |
| Immutable where possible | Replace, do not repair | Swap in a new server instead of patching by hand |
A hardening checklist
1. Accounts and logins
Every account is a possible way in. Fewer accounts with less power means less risk.
cat /etc/passwdsudo grep -r NOPASSWD /etc/sudoersawk -F: '$3 == 0 {print $1}' /etc/passwd # only root should have UID 0awk -F: '$2 == "" {print $1}' /etc/shadow # no empty passwordssudo lastlog # who logged in when- Turn off root SSH login and password login (see the SSH lesson).
- Lock or remove unused accounts:
sudo usermod -L olduserorsudo userdel -r olduser. - Give everyone their own named account (or SSO). Never share logins, so every action can be traced to a person.
- Keep sudo rules small. Edit them with
visudo, in files under/etc/sudoers.d/.
2. Services and ports
Every running service and open port is a door an attacker can knock on.
ss -tulpnsystemctl list-units --type=service --state=runningFor each open port, ask: "Does this need to run here? Does it need to be reachable from outside?" Turn off what is not needed:
sudo systemctl disable --now cups avahi-daemon3. Patching (updates)
Most attacks use holes that already have a fix. Updating closes them.
sudo apt install unattended-upgrades # Ubuntu: automatic security updatessudo dpkg-reconfigure -plow unattended-upgradessudo dnf install dnf-automatic # RHEL familysudo systemctl enable --now dnf-automatic.timerKernel updates only take effect after a reboot. needrestart (Debian) or needs-restarting -r (RHEL) tells you if a reboot is waiting.
In the cloud, the cleaner way is to rebuild the server image with the latest patches and roll out new servers. You will do this with Packer later in this course.
4. File permissions
A file anyone can change, or a program that runs as root, is an easy target.
sudo find / -xdev -perm -0002 -type f 2>/dev/null # world-writable filessudo find / -xdev -perm -4000 -type f 2>/dev/null # setuid binaries- Secrets should be readable only by their service:
chmod 600, owned by the service's user. - Mount
/tmpwithnoexec,nosuid,nodevwhere you can. Then attackers cannot run programs they drop there.
5. Kernel and network settings
Safer settings for how the kernel handles network traffic, in /etc/sysctl.d/99-hardening.conf (the next lesson explains sysctl):
net.ipv4.conf.all.accept_redirects = 0net.ipv4.conf.all.send_redirects = 0net.ipv4.conf.all.rp_filter = 1net.ipv4.tcp_syncookies = 1kernel.kptr_restrict = 2kernel.dmesg_restrict = 16. SELinux and AppArmor
Normal permissions control who can open a file. SELinux (Red Hat family) and AppArmor (Ubuntu) also control what each program is allowed to do, even if it runs as root.
If nginx is hacked, its policy still stops it reading /etc/shadow (the password file).
Think of it like: a hotel key card that only opens your room, even though you are inside the hotel.
getenforce # SELinux: Enforcing, Permissive or Disabledsudo ausearch -m avc -ts recent # recent SELinux denialssudo aa-status # AppArmor profilesWhen SELinux blocks something that should be allowed, fix the label or the policy. For example: restorecon -Rv /var/www, or setsebool -P httpd_can_network_connect 1.
Do not turn SELinux off to make a problem go away. That removes a whole layer of protection.
7. Auditing
Recording who changed important files and who ran what.
If something goes wrong, you can see exactly what happened.
sudo apt install auditdsudo auditctl -w /etc/passwd -p wa -k identity # log writes to /etc/passwdsudo ausearch -k identitySend auth.log, audit logs and sudo logs to a central system. Then an attacker cannot delete their tracks on the server.
8. Blocking attacks and spotting changes
- fail2ban blocks IPs after repeated failed logins.
- AIDE remembers a fingerprint of each important file and reports unexpected changes.
- Cloud tools like AWS GuardDuty, Inspector and Security Hub watch the whole account for threats and weak spots.
Benchmarks and automation
The CIS Benchmarks are detailed, widely trusted hardening guides for each Linux distribution.
You do not apply hundreds of settings by hand. You use tools:
| Tool | Use |
|---|---|
OpenSCAP / oscap | Scan a system against CIS or STIG rules |
| Lynis | A quick security check with suggestions |
| Ansible roles | Apply the same hardening to every server |
| Packer | Build a hardened "golden image" once, and use it everywhere |
| CIS hardened AMIs | Ready-hardened images from the AWS Marketplace |
lynis audit systemThe professional way: harden in code (Ansible or Packer), scan in the pipeline, and fail the build if the score drops.
Containers need hardening too
- Run as a non-root user (
USER 10001in the Dockerfile). - Use small base images (distroless, Alpine or "slim" versions). Less software = fewer holes.
- Use a read-only filesystem and remove Linux capabilities the app does not need.
- Scan images for known holes with Trivy or Twistlock in CI.
Real-world scenario: passing a security audit
An auditor asks for proof that production servers are hardened. Instead of screenshots, you show:
- The Packer template that builds the golden image with the CIS role applied.
- The pipeline job that runs OpenSCAP, and its report scoring above the agreed level.
- Automatic security updates switched on, plus the monthly image rebuild schedule.
- Central logs of every SSH login and sudo command.
Repeatable, automatic proof is what auditors want, and it is far less work than checking servers by hand.
Common mistakes
- Turning off SELinux or AppArmor instead of fixing the policy.
- Hardening one server by hand, so the next server is different.
- Never rebooting after kernel updates, which leaves the holes open.
- Keeping secrets in plain files that anyone can read, or in shell history.
Practice
- List every open port on the server and decide which ones should be reachable from outside.
- Find any accounts with UID 0 other than root.
- Write three sysctl lines that make network behaviour safer.
- Explain why turning off SELinux to fix a permission problem is a bad idea, and what you would do instead.
Cheat sheet
| Task | Command |
|---|---|
| Open ports | ss -tulpn |
| Running services | systemctl list-units --type=service --state=running |
| Lock an account | usermod -L user |
| Automatic updates | unattended-upgrades / dnf-automatic |
| SELinux mode | getenforce |
| Check a system | lynis audit system |
| Watch a file | auditctl -w path -p wa -k key |
Key takeaways
- A new server is not safe by default. Hardening closes the doors you do not need.
- Give every person and program only the access it needs.
- Install security updates quickly, and reboot for kernel updates.
- Never turn off SELinux or AppArmor. Fix the rule instead.
- Do hardening as code (Ansible, Packer), so every server is protected the same way.