Do these on a disposable Ubuntu 24.04 or Rocky Linux 9 VM (or a container with systemd where noted). Never practice destructive commands on a machine you care about. Open the hint only after you have tried for 10 minutes.
Beginner
A1. Filesystem navigation and hierarchy ๐ข
Objective: Get fluent with the directory layout and basic file operations.
Tasks
- Create
~/lab/a1/{docs,src,tmp}with one command. - Create five files in
srcusingtouch, and copy two intodocs. - Move one file from
srctotmpand rename it toold.txt. - Use
tree(orfind) to show the structure, then deletetmprecursively. - Print what
/etc,/var/log,/procand/usr/localare used for, in your own words.
Expected outcome: The final tree has docs (2 files) and src (4 files), tmp is gone, and you can explain the four directories.
Hints
mkdir -p ~/lab/a1/{docs,src,tmp}, touch ~/lab/a1/src/f{1..5}.txt, cp, mv, rm -r. Brace expansion is done by the shell, not by mkdir.
Bonus: Do task 1 to 4 in a single script that exits non-zero if any step fails.
A2. Permissions and ownership ๐ข
Objective: Read and set permissions in both symbolic and octal form.
Tasks
- Create
secret.txtand set it so only the owner can read and write. - Create a script
hello.shand make it executable only for the owner. - Create a directory
sharedwhere the groupdevscan write. - Show
ls -loutput and decode every permission string by hand. - Show that a user who is not in
devscannot entersharedafterchmod 770.
Expected outcome: secret.txt is -rw-------, hello.sh is -rwx------, shared is drwxrwx--- owned by group devs.
Hints
chmod 600, chmod u+x, groupadd devs, chgrp devs shared, chmod 770 shared. Test with sudo -u otheruser ls shared. Remember a directory needs x to be entered.
Bonus: Make new files in shared inherit group devs automatically using the setgid bit (chmod g+s) and prove it.
A3. Users and groups ๐ข
Objective: Manage accounts the way a sysadmin would.
Tasks
- Create users
aliceandbobwith home directories and bash as the shell. - Add
alicetosudo(Debian/Ubuntu) orwheel(RHEL), but notbob. - Lock
bob's password, then unlock it. - Set a password-expiry policy for
aliceof 90 days maximum. - Delete
bobincluding his home directory.
Expected outcome: id alice shows the admin group, chage -l alice shows 90 days, getent passwd bob returns nothing.
Hints
useradd -m -s /bin/bash, usermod -aG sudo alice (the -a matters, without it you replace the group list), passwd -l/-u, chage -M 90 alice, userdel -r bob. Check /etc/passwd, /etc/shadow and /etc/group.
Bonus: Write a script that reads usernames from a file and creates them idempotently (skipping existing ones).
A4. Text processing pipeline ๐ข
Objective: Use grep, awk, sed, sort and uniq on a real log.
Tasks
- Generate a fake access log with 1,000 lines (or use
/var/log/auth.logorjournalctloutput). - Count requests per IP and show the top 5.
- Extract all lines with HTTP status 5xx.
- Replace every IP address with
x.x.x.xusingsed(for anonymising). - Print the 3rd and 7th fields of each line with
awk.
Expected outcome: A one-liner pipeline for each task, each producing correct output on your sample.
Hints
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -5. For 5xx: awk '$9 ~ /^5/' access.log. For anonymising: sed -E 's/([0-9]{1,3}\.){3}[0-9]{1,3}/x.x.x.x/g'.
Bonus: Show requests per minute with cut -c on the timestamp, then find the peak minute.
A5. Find files and clean up safely ๐ข
Objective: Use find and du to locate space hogs and stale files.
Tasks
- Create 20 files of mixed sizes with
ddorfallocate, some backdated withtouch -d. - Find files larger than 10 MB.
- Find files older than 7 days.
- Show the five largest directories under
/varwithdu. - Delete the old files using
find ... -delete, after first listing what would go.
Expected outcome: Only files that match both criteria are removed, and you ran the list command before the delete command.
Hints
find . -type f -size +10M, find . -type f -mtime +7, du -xh /var --max-depth=2 | sort -rh | head, find . -type f -mtime +7 -print then swap -print for -delete. Put -delete last, since order matters.
Bonus: Find files by owner or permissions (for example world-writable) with -perm -0002.
A6. Processes and signals ๐ข
Objective: Observe, signal and control processes.
Tasks
- Start
sleep 600in the background, find its PID withpgrepandps. - Pause it with
SIGSTOP, resume withSIGCONTand verify the state letter inps. - Terminate it with
SIGTERM. - Write a bash script that traps
SIGTERMandSIGINT, prints a message and exits cleanly; send it signals from another terminal. - Change the priority of a CPU-burning loop with
niceandrenice.
Expected outcome: You can show states S, T, and the trap message on kill -15, and the NI column changing in top.
Hints
kill -STOP PID, ps -o pid,stat,cmd -p PID, trap 'echo bye; exit 0' TERM INT. For the loop: yes > /dev/null &, then renice +10 -p PID. kill -9 cannot be trapped.
Bonus: Create a zombie process on purpose (a parent that does not wait) and identify it.
A7. Install and manage packages and services ๐ข
Objective: Install software and manage it with systemd.
Tasks
- Install
nginxwithaptordnf. - Check that it is enabled and running, and where its config and logs live (
dpkg -Lorrpm -ql). - Stop it, disable it, then enable and start it in one command.
- View its last 20 log lines through
journalctl. - Find which package owns
/usr/sbin/nginx.
Expected outcome: systemctl is-enabled nginx and is-active return enabled and active, and you can name the owning package.
Hints
systemctl enable --now nginx, journalctl -u nginx -n 20, dpkg -S /usr/sbin/nginx or rpm -qf /usr/sbin/nginx. On Debian-based systems services start on install, on RHEL they do not.
Bonus: Hold the package at its current version (apt-mark hold) or lock it (dnf versionlock).
A8. SSH keys and config ๐ข
Objective: Set up key-based login and a client config.
Tasks
- Generate an
ed25519key pair with a passphrase. - Install the public key on a second machine (or a second local user) with
ssh-copy-id. - Create
~/.ssh/configwith aHostalias that sets user, hostname and key. - Disable password authentication on the server and confirm it is refused.
- Use
ssh-agentso you type the passphrase once.
Expected outcome: ssh myalias logs in with the key, and ssh -o PubkeyAuthentication=no fails with Permission denied (publickey).
Hints
ssh-keygen -t ed25519, chmod 600 ~/.ssh/config, eval "$(ssh-agent)"; ssh-add. Server side: sshd -t before systemctl reload ssh. Permissions on ~/.ssh (700) and authorized_keys (600) are the number one reason keys fail.
Bonus: Copy a file with scp and with rsync -avz -e ssh and compare the speed on a second run.
A9. Disk usage, mounts and fstab ๐ข
Objective: Attach a new disk and mount it persistently.
Tasks
- Create a loop-backed "disk":
truncate -s 1G disk.img; losetup -f --show disk.img. - Partition it or use it whole, format it with
ext4. - Mount it on
/mnt/data, write a file, then unmount. - Add an entry using the filesystem UUID to
/etc/fstabwithnofail. - Test with
mount -aand show it withfindmntanddf -hT.
Expected outcome: /mnt/data mounts with mount -a, using a UUID entry, without a reboot.
Hints
mkfs.ext4 /dev/loop0, blkid /dev/loop0, line: UUID=<uuid> /mnt/data ext4 defaults,nofail 0 2. Always run mount -a after editing fstab, since a bad line can drop you into emergency mode at boot. Detach with losetup -d.
Bonus: Show the difference in df -h and df -i after creating 100,000 empty files.
A10. Basic network diagnostics ๐ข
Objective: Inspect network configuration and test connectivity.
Tasks
- Show your IP addresses, default route and DNS servers.
- List all listening TCP ports and the owning processes.
- Resolve
example.comwithdigand withgetent hosts; explain why they can differ. - Test whether port 443 is reachable on a remote host using
nc -vzandcurl -v. - Trace the path with
tracerouteormtr.
Expected outcome: A short note identifying your interface, gateway, resolver and the first slow hop (if any).
Hints
ip -br a, ip r, resolvectl status, ss -tulpn, dig +short example.com, nc -vz host 443. getent hosts follows nsswitch.conf (including /etc/hosts), while dig talks directly to DNS.
Bonus: Add a temporary entry to /etc/hosts and show which tool sees it and which does not.
Intermediate
A11. Write a production systemd service ๐ก
Objective: Run an app as a managed, hardened service.
Tasks
- Write a small app (Python
http.serveris fine) that listens on port 9000. - Create a dedicated system user with
nologin. - Write
/etc/systemd/system/myapp.servicewithUser=,Restart=on-failure, andEnvironment=. - Add at least five hardening options (
NoNewPrivileges,ProtectSystem,PrivateTmp, ...). - Kill the process with
-9and prove it comes back; checksystemd-analyze security myapp.
Expected outcome: Service is active, restarts within seconds after a kill, and has an exposure score below 5.0 (MEDIUM or better).
Hints
systemctl daemon-reload after each edit. Use ReadWritePaths= with ProtectSystem=strict. Use journalctl -u myapp -f to watch restarts. Status 203/EXEC means a bad ExecStart path.
Bonus: Add MemoryMax= and CPUQuota= and prove the limit with a memory-hungry process.
A12. systemd timer replacing cron ๐ก
Objective: Schedule a job with a systemd timer.
Tasks
- Write a oneshot service that appends a timestamp to
/var/log/tick.log. - Write a timer that runs it every 2 minutes after boot and with
Persistent=true. - Enable the timer and verify with
systemctl list-timers. - Validate a calendar expression with
systemd-analyze calendar "Mon..Fri 02:30". - Stop the machine's timer for 5 minutes and show catch-up behaviour on restart.
Expected outcome: tick.log receives entries; list-timers shows NEXT and LAST columns populated.
Hints
Enable the timer (systemctl enable --now tick.timer), not the service. Use OnUnitActiveSec=2min and OnBootSec=1min. Persistent=true only works with OnCalendar=.
Bonus: Add RandomizedDelaySec= and OnFailure= pointing to a unit that logs a failure message.
A13. Bash backup script with retention ๐ก
Objective: Write a robust, cron-ready backup script.
Tasks
- Write
backup.shthat archives a directory to/var/backupswith a timestamped name. - Use
set -euo pipefail, atrapfor cleanup andflockto prevent overlap. - Verify the archive (
tar -tzf) and write a SHA-256 file. - Delete backups older than 7 days.
- Schedule it with cron at 02:00 and test a restore into a temp directory.
Expected outcome: Exit code 0 on success and non-zero when the source is missing, a log line for each run, restored data equals source (diff -r).
Hints
Cron has a minimal PATH, so use absolute paths. exec 9>/run/x.lock; flock -n 9 || exit 1. Test failure with a wrong SRC and check echo $?. Use find ... -mtime +7 -delete for retention.
Bonus: Add an off-host copy with rsync or aws s3 cp and a freshness check that alerts if the newest backup is over 26 hours old.
A14. logrotate for a custom application log ๐ก
Objective: Configure and test rotation without waiting a day.
Tasks
- Write an app that logs a line per second to
/var/log/myapp/app.log. - Create
/etc/logrotate.d/myappwithdaily,rotate 7,compress,delaycompress,missingok,notifempty. - Dry-run with
logrotate -dand force withlogrotate -f. - Solve the "app keeps writing to the rotated file" problem, first with
copytruncate, then with apostrotatesignal. - Explain the trade-off between the two.
Expected outcome: After forcing, you see app.log, app.log.1 (uncompressed because of delaycompress), and new lines go to the new app.log.
Hints
copytruncate can lose a few lines between copy and truncate; postrotate with kill -HUP or systemctl reload needs the app to reopen files. Check state in /var/lib/logrotate/status. Permissions errors often need su user group.
Bonus: Rotate by size (size 50M) and show it triggers only when the size passes.
A15. nginx reverse proxy and load balancing ๐ก
Objective: Front two app instances with nginx.
Tasks
- Start two backends on ports 8001 and 8002 that print different identifiers.
- Configure an
upstreamwith both servers andproxy_passto it. - Pass
Host,X-Real-IPandX-Forwarded-Forheaders. - Show round-robin with
for i in {1..6}; do curl -s localhost; done. - Stop one backend and show failover, then check the error log.
Expected outcome: Alternating responses; with one backend down the other serves all requests with no 5xx visible after the first failed attempt.
Hints
nginx -t && nginx -s reload. Use max_fails=2 fail_timeout=10s on upstream servers. ip_hash; gives sticky behaviour. The error log shows connect() failed (111: Connection refused) for the dead backend.
Bonus: Add a rate limit with limit_req_zone and prove it returns 503 (or 429 with limit_req_status 429) under ab or hey.
A16. Firewall with nftables or ufw ๐ก
Objective: Build a default-deny firewall safely.
Tasks
- Set default deny incoming, allow established/related, allow loopback.
- Allow SSH from one source subnet only, and 80/443 from anywhere.
- Add a rate limit on new SSH connections.
- Log and drop everything else with a limit on the log rate.
- Persist the rules across reboot and test from another host with
nmap.
Expected outcome: nmap from outside shows only 80 and 443 open (22 filtered unless from the allowed subnet), and rules survive a reboot.
Hints
For ufw: ufw limit 22/tcp, ufw allow from 10.0.0.0/24 to any port 22. For nftables: write /etc/nftables.conf, check with nft -c -f, systemctl enable nftables. Schedule a rollback (at now + 5 min with ufw disable) before testing remotely.
Bonus: Block an abusive IP with an nftables set that has a timeout.
A17. LVM: create, extend and shrink ๐ก
Objective: Manage storage flexibly with LVM.
Tasks
- Create two loop devices and make them physical volumes.
- Create a volume group, then a 500 MB logical volume with
xfsorext4. - Mount it, fill it to 90% and extend the LV online with
lvextend -r. - Add the second PV to the VG to get extra space first if needed.
- Take a snapshot, change data, and roll back.
Expected outcome: df -h shows the larger filesystem without unmounting, and the snapshot restores the old content.
Hints
pvcreate, vgcreate, lvcreate -L 500M -n data vg0, lvextend -r -L +300M /dev/vg0/data, vgextend. xfs cannot shrink. Use lvs, vgs, pvs to inspect. Snapshot: lvcreate -s -n snap -L 200M vg0/data, merge with lvconvert --merge.
Bonus: Replace a "failing" PV with pvmove and remove it from the VG without downtime.
A18. Performance triage under load ๐ก
Objective: Identify the bottleneck with the right tool.
Tasks
- Generate CPU load with
stress-ng --cpu 2, then find it withtopandpidstat. - Generate disk I/O with
ddorfioand spot it withiostat -xz 1andiotop. - Generate memory pressure with
stress-ng --vm 1 --vm-bytes 80%and watchvmstat 1. - For each case, write one sentence: what metric proved the bottleneck.
- Compare load average with
nproc, and explain what a load of 8 means on 4 cores.
Expected outcome: A table of three scenarios with symptom, tool, and metric (for example %util near 100 and high await for disk).
Hints
High wa in top means waiting on I/O. si/so columns in vmstat mean swapping. free -m "available" is the real headroom. mpstat -P ALL 1 shows single-core saturation.
Bonus: Use sar (from sysstat) to look back at yesterday's CPU history.
A19. Troubleshoot a broken server (planted faults) ๐ก
Objective: Diagnose faults methodically instead of guessing.
Tasks
- Have a friend (or a script) break five things: fill
/varinodes, stop nginx, change a file's permissions, breakfstab, add a bad DNS server. - For each symptom write what you checked first and why.
- Fix each one and note the root cause.
- Write a runbook of five entries: symptom, command, fix.
- Time yourself; aim for under 5 minutes per fault.
Expected outcome: All five faults fixed, with a runbook that another engineer can follow.
Hints
df -h and df -i, systemctl --failed, journalctl -xe, namei -l /path for permission issues, findmnt --verify for fstab, resolvectl query example.com for DNS. Check resources first, then the service, then the app.
Bonus: Automate the faults as a script so you can re-run the exercise with different random picks.
A20. Harden SSH and add fail2ban ๐ก
Objective: Reduce the attack surface of remote access.
Tasks
- Create
/etc/ssh/sshd_config.d/10-hardening.confwithPermitRootLogin no,PasswordAuthentication no,AllowUsers,MaxAuthTries 3. - Validate with
sshd -tandsshd -T; test from a second session before closing the first. - Install
fail2banand enable thesshdjail with a 1 hour ban. - Trigger a ban with failed logins and view it with
fail2ban-client status sshd. - Unban your IP and add it to
ignoreip.
Expected outcome: Root and password logins fail, repeated failures create a ban visible in the firewall.
Hints
Check for cloud-init drop-ins that re-enable passwords. On Ubuntu 24.04 use backend = systemd. fail2ban-client set sshd unbanip IP. Keep console access as a fallback.
Bonus: Add AllowGroups ssh-users, move to certificate-based SSH or enable AuthenticationMethods publickey,keyboard-interactive for 2FA.
Advanced
A21. Build a container by hand with namespaces and cgroups ๐ด
Objective: Prove that a container is just isolated Linux processes.
Tasks
- Extract a minimal root filesystem (for example
docker export $(docker create alpine) | tar -x -C rootfs, ordebootstrap). - Start a shell with
unshare --pid --mount --uts --net --fork --mount-proc chroot rootfs /bin/sh. - Show that PID 1 inside is your shell and the hostname is independent.
- Create a cgroup v2 at
/sys/fs/cgroup/demo, setmemory.maxto 50M andcpu.maxto20000 100000, and move the process in. - Run a memory hog inside and show the OOM kill in
dmesgandmemory.events.
Expected outcome: A shell with its own PID, UTS and mount namespace limited to 50 MB and 20% of one CPU, with evidence of the OOM kill.
Hints
echo $$ > /sys/fs/cgroup/demo/cgroup.procs, echo 50M > memory.max. You may need echo +memory +cpu > /sys/fs/cgroup/cgroup.subtree_control. lsns and /proc/<pid>/ns/ show namespaces. Use nsenter -t PID -n ip a to enter from outside.
Bonus: Give the namespace network access with a veth pair, a bridge and iptables MASQUERADE.
A22. Trace a hung or slow process ๐ด
Objective: Find the root cause of a stuck process without restarting it.
Tasks
- Write (or use) a program that hangs: one blocked on a read from a FIFO, one in a busy loop, one blocked on a lock file.
- Use
strace -p PID -f -ttto see the syscall each one is stuck in. - Use
ls -l /proc/PID/fd,cat /proc/PID/stack(root),cat /proc/PID/wchanandlsof -p PID. - Use
perf top -p PIDorperf record -gto profile the busy loop. - Write the findings: what each tool showed and which would you use first in production.
Expected outcome: For each program you can state the exact blocking call, the file or resource involved, and the evidence.
Hints
A process stuck in read(3, ... on an FD that /proc/PID/fd/3 shows as a FIFO or socket tells you who it waits for. State D with a stack in nfs_ or io_schedule points to storage. strace -c summarises time per syscall. Mind the overhead of strace on production.
Bonus: Use bpftrace or bcc (opensnoop, execsnoop) to trace system-wide without stopping the process.
A23. Kernel tuning for a high-traffic server ๐ด
Objective: Tune and validate sysctl and limits with measured evidence.
Tasks
- Baseline with
wrkorabagainst nginx and record requests per second and errors. - Inspect and raise
net.core.somaxconn,net.ipv4.tcp_max_syn_backlog,fs.file-maxand the serviceLimitNOFILE. - Tune
net.ipv4.ip_local_port_range, enabletcp_tw_reusefor outbound-heavy clients and setvm.swappiness. - Persist in
/etc/sysctl.d/99-tuning.confand apply withsysctl --system. - Re-run the benchmark, compare, and document which change helped and which did not.
Expected outcome: A before/after table with a justification for every kept setting, and no cargo-culted values.
Hints
ss -s and nstat -az | grep -i listen show overflows. Too many open files is solved by LimitNOFILE in the unit, not just sysctl. Change one variable at a time. Do not "tune" tcp_tw_recycle (removed from the kernel).
Bonus: Plot a latency histogram (p50/p99) before and after, and test with irqbalance or taskset CPU pinning.
A24. Incident: OOM kills and disk-full postmortem ๐ด
Objective: Reproduce two classic outages and write the postmortem.
Tasks
- Reproduce an OOM kill (service with no memory limit plus a leak) and find it with
dmesg -T | grep -i 'out of memory'andjournalctl -k. - Read the OOM report: which process was chosen,
oom_score_adj, memory at the time. - Prevent a repeat with
MemoryMax=,OOMScoreAdjust=and an alert onavailablememory. - Reproduce a full-disk event where
dfshows 100% butdushows less (deleted-but-open file); locate it withlsof +L1and fix without restart if possible. - Write a one-page blameless postmortem for each with timeline, root cause, detection gap and action items.
Expected outcome: Two postmortems, each with evidence commands and a prevention that is testable.
Hints
: > /proc/PID/fd/N truncates a deleted open file. systemd-oomd and cgroup-level OOM differ from global OOM. Check df -i too. Rotated logs without a reopen are the usual deleted-file cause.
Bonus: Write a Prometheus alert rule for node_memory_MemAvailable_bytes and node_filesystem_avail_bytes with predictive predict_linear.
A25. CIS-style hardening and audit with auditd ๐ด
Objective: Bring a server near a recognised security baseline and prove it.
Tasks
- Remove unneeded packages and disable unused services; list listening sockets before and after.
- Set kernel hardening in
/etc/sysctl.d/:kernel.kptr_restrict,net.ipv4.conf.all.rp_filter,net.ipv4.conf.all.accept_redirects=0,kernel.randomize_va_space=2. - Mount
/tmpwithnodev,nosuid,noexecand verify an executable cannot run from it. - Install
auditdand write rules watching/etc/passwd,/etc/sudoers,/etc/ssh/sshd_configandexecveby root; trigger and search events withausearch. - Run
lynis audit system(or OpenSCAP) before and after, and record the score and the top five fixes.
Expected outcome: Lynis hardening index improves measurably; audit events show who changed a watched file.
Hints
auditctl -w /etc/passwd -p wa -k identity, persist in /etc/audit/rules.d/*.rules and augenrules --load. ausearch -k identity -i. Beware noexec on /tmp breaking installers; test your package manager. Make changes via configuration management so they are reproducible.
Bonus: Express the whole hardening as an Ansible role and run it idempotently (second run changes nothing).