TExcelTAD
Home › Linux Server Administration › Server Administration Exercises

Server Administration Exercises

Each exercise starts with a broken or unfinished piece of server configuration, checked with the same tool you would use on a real server. Run the starter first: its output shows what is wrong. Fix it in the editor (or on your practice VM) until you get the expected output, then compare with the solution.

Exercise 1: Fix the unit file

Topics: systemd Units & Unit Files, Writing a Service Unit, cgroups v2

A colleague wrote this unit for a queue worker. It "works", but four settings are silently ignored. Find and fix them so that systemd-analyze verify prints nothing.

bash · try it yourself
cat > worker.service <<'EOF'
[Unit]
Description=Queue worker
Wants=network-online.target
Afer=network-online.target

[Service]
Type=exec
ExecStart=/usr/bin/python3 -m http.server 8000
Restart=on_failure
RestartSec=5s
MemoryMax=512MB

[Instal]
WantedBy=multi-user.target
EOF
systemd-analyze verify ./worker.service && echo "worker.service: clean"
/home/learner/worker.service:4: Unknown key name 'Afer' in section 'Unit', ignoring.
/home/learner/worker.service:9: Failed to parse service restart specifier, ignoring: on_failure
/home/learner/worker.service:11: Invalid memory limit '512MB', ignoring: Invalid argument
/home/learner/worker.service:13: Unknown section 'Instal'. Ignoring.
worker.service: clean

Expected output:

text
worker.service: clean
Show solution
ini
[Unit]
Description=Queue worker
Wants=network-online.target
After=network-online.target          # was "Afer"

[Service]
Type=exec
ExecStart=/usr/bin/python3 -m http.server 8000
Restart=on-failure                   # hyphen, not underscore
RestartSec=5s
MemoryMax=512M                       # systemd knows K/M/G/T, not "MB"

[Install]                            # was "[Instal]": the whole section was ignored
WantedBy=multi-user.target

Note that verify still exits with 0 for these warnings: in CI, treat any output as a failure.

Exercise 2: From cron to OnCalendar

Topics: systemd Timers

Translate four cron schedules into calendar expressions. The starter uses cron syntax, which systemd-analyze calendar rejects.

Cron Meaning
30 7 * * 1-5 07:30 on weekdays
*/10 * * * * every 10 minutes
(not possible in one cron line) 04:00 on the first Monday of every month
0 0 1 1,4,7,10 * midnight on the first day of each quarter
bash · try it yourself
for spec in "30 7 * * 1-5" "*/10 * * * *" "first monday 04:00" "0 0 1 1,4,7,10 *"; do
  echo "== $spec"
  systemd-analyze calendar --base-time="2026-01-15 10:00:00 UTC" --iterations=2 "$spec" 2>&1 | grep -E 'Failed|elapse|Iteration'
done
== 30 7 * * 1-5
Failed to parse calendar specification '30 7 * * 1-5': Invalid argument
== */10 * * * *
Failed to parse calendar specification '*/10 * * * *': Invalid argument
== first monday 04:00
Failed to parse calendar specification 'first monday 04:00': Invalid argument
== 0 0 1 1,4,7,10 *
Failed to parse calendar specification '0 0 1 1,4,7,10 *': Invalid argument

Expected output (base time Thursday 2026-01-15 10:00 UTC):

text
== Mon..Fri *-*-* 07:30:00
    Next elapse: Fri 2026-01-16 07:30:00 UTC
   Iteration #2: Mon 2026-01-19 07:30:00 UTC
== *:0/10
    Next elapse: Thu 2026-01-15 10:10:00 UTC
   Iteration #2: Thu 2026-01-15 10:20:00 UTC
== Mon *-*-01..07 04:00:00
    Next elapse: Mon 2026-02-02 04:00:00 UTC
   Iteration #2: Mon 2026-03-02 04:00:00 UTC
== *-01,04,07,10-01 00:00:00
    Next elapse: Wed 2026-04-01 00:00:00 UTC
   Iteration #2: Wed 2026-07-01 00:00:00 UTC
Show solution
bash
for spec in "Mon..Fri *-*-* 07:30:00" "*:0/10" "Mon *-*-01..07 04:00:00" "*-01,04,07,10-01 00:00:00"; do
  echo "== $spec"
  systemd-analyze calendar --base-time="2026-01-15 10:00:00 UTC" --iterations=2 "$spec" 2>&1 | grep -E 'Failed|elapse|Iteration'
done

The "first Monday" works because systemd combines the weekday and the date with AND: a Monday that is also one of the days 1 to 7. Cron combines them with OR, which is why it can't express it.

Exercise 3: SSH hardening that actually applies

Topics: Hardening the SSH Server

The main sshd_config below was "hardened", but a cloud-init drop-in and two leftover lines undo it. Without touching 50-cloud-init.conf, make the effective configuration (as printed by sshd -T) show: no root login, no passwords, no keyboard-interactive, AllowGroups ssh-users, MaxAuthTries 3, no X11 forwarding.

bash · try it yourself
ssh-keygen -q -t ed25519 -N "" -f hostkey
mkdir -p sshd_config.d
echo "PasswordAuthentication yes" > sshd_config.d/50-cloud-init.conf
cat > sshd_config <<EOF
Include $PWD/sshd_config.d/*.conf
HostKey $PWD/hostkey
PidFile $PWD/sshd.pid
PermitRootLogin yes
X11Forwarding yes
PasswordAuthentication no
EOF
sshd -t -f sshd_config && sshd -T -f sshd_config | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|allowgroups|maxauthtries|x11forwarding) '
maxauthtries 6
permitrootlogin yes
passwordauthentication yes
kbdinteractiveauthentication yes
x11forwarding yes

Expected output:

text
maxauthtries 3
permitrootlogin no
passwordauthentication no
kbdinteractiveauthentication no
x11forwarding no
allowgroups ssh-users
Show solution

Add a drop-in that sorts before 50-cloud-init.conf, because in sshd_config the first value wins:

bash
cat > sshd_config.d/10-hardening.conf <<'EOF'
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
AllowGroups ssh-users
MaxAuthTries 3
X11Forwarding no
EOF

The PermitRootLogin yes and X11Forwarding yes lines in the main file now come too late to matter, but delete them anyway: the next person to read the file will believe them.

Exercise 4: A narrow sudo rule

Topics: sudo & sudoers

Requirements: the deploy user may restart and query the status of app.service without a password; members of the group ops may read that service's journal (any extra journalctl options) with their password. Nothing else. The starter fails the strict check and is far too broad.

bash · try it yourself
cat > 60-app <<'EOF'
deploy ALL=(ALL) NOPASSWD: systemctl
%ops   ALL=(ALL) ALL
EOF
visudo -c -s -f 60-app
echo "exit code: $?"
60-app:1:28: expected a fully-qualified path name
deploy ALL=(ALL) NOPASSWD: systemctl
                           ^~~~~~~~~
exit code: 1

Expected output:

text
60-app: parsed OK
Show solution
bash
cat > 60-app <<'EOF'
Cmnd_Alias APP_DEPLOY = /usr/bin/systemctl restart app.service, /usr/bin/systemctl status app.service
Cmnd_Alias APP_LOGS   = /usr/bin/journalctl -u app.service *
deploy ALL=(root) NOPASSWD: APP_DEPLOY
%ops   ALL=(root) APP_LOGS
EOF
visudo -c -s -f 60-app

Full paths, exact arguments for systemctl, and (root) instead of (ALL). The * after journalctl -u app.service allows options such as -n 100 or --since; journalctl has no option that runs commands, but keep in mind that its pager (less) does, so set Defaults:%ops env_keep -= SYSTEMD_PAGER or tell people to add --no-pager, and consider SYSTEMD_LESS / Defaults noexec for that rule.

Exercise 5: Where did the disk go?

Topics: When the Disk Is Full

Under srv/ someone filled the disk, and a "daemon" still holds a deleted log open. Complete the three TODO lines so the session prints the three biggest directories directly below srv, the single biggest file, and the deleted-but-open file.

bash · try it yourself
mkdir -p srv/app/logs srv/app/cache srv/db srv/uploads/2025 srv/uploads/2026
head -c 25M /dev/zero > srv/app/logs/app.log
head -c 3M  /dev/zero > srv/app/cache/thumbs.bin
head -c 40M /dev/zero > srv/db/data.db
for i in 1 2 3 4 5 6; do head -c 2M /dev/zero > srv/uploads/2026/img$i.jpg; done
head -c 1M  /dev/zero > srv/uploads/2025/old.jpg
head -c 30M /dev/zero > srv/app/logs/debug.log
sleep 300 3>>srv/app/logs/debug.log &
rm srv/app/logs/debug.log
# --- your part
echo "TODO: three biggest directories below srv"
echo "TODO: the biggest file, in MB"
echo "TODO: open files whose name was deleted"
kill %1
TODO: three biggest directories below srv
TODO: the biggest file, in MB
TODO: open files whose name was deleted

Expected output:

text
41M	srv/db
29M	srv/app
14M	srv/uploads
40 MB srv/db/data.db
/home/learner/srv/app/logs/debug.log (deleted)
Show solution
bash
du -xh --max-depth=1 srv | sort -rh | sed -n '2,4p'          # line 1 is srv itself
find srv -xdev -type f -printf '%s %p\n' | sort -rn | head -1 | awk '{printf "%d MB %s\n", $1/1048576, $2}'
find /proc/[0-9]*/fd -lname '*(deleted)' -printf '%l\n' 2>/dev/null

srv/app shows 29M although app.log and the cache add up to 28 MB on paper: du -h rounds up. The 30 MB debug.log appears in no du total, which is the whole point of the third line.

Exercise 6: A fail2ban filter that can't be fooled

Topics: fail2ban

The app logs failed logins as WARN auth: login failed user=<name> ip=<address>. The starter filter matches too much: a failed payment, and a line where the attacker put a second ip= into the user name field. Write a filter that matches exactly the three genuine failed logins from 203.0.113.5.

bash · try it yourself
cat > app.log <<'EOF'
2026-01-15 10:00:01 WARN auth: login failed user=bob ip=203.0.113.5
2026-01-15 10:00:02 INFO auth: login ok user=ada ip=192.0.2.10
2026-01-15 10:00:03 WARN auth: login failed user=root ip=203.0.113.5
2026-01-15 10:00:04 WARN auth: login failed user=x ip=1.2.3.4 ip=198.51.100.7
2026-01-15 10:00:05 WARN billing: payment failed user=carol ip=192.0.2.44
2026-01-15 10:00:06 WARN auth: login failed user=eve ip=203.0.113.5
EOF
FILTER='failed .* ip=<HOST>'
fail2ban-regex app.log "$FILTER" | grep -E '^Lines'
fail2ban-regex --print-all-matched app.log "$FILTER" | sed -n '/Matched line/,/^`-/p' | awk '/^\|  [0-9]/ {print $NF}'
Lines: 6 lines, 0 ignored, 5 matched, 1 missed
ip=203.0.113.5
ip=203.0.113.5
ip=198.51.100.7
ip=192.0.2.44
ip=203.0.113.5

Expected output:

text
Lines: 6 lines, 0 ignored, 3 matched, 3 missed
ip=203.0.113.5
ip=203.0.113.5
ip=203.0.113.5
Show solution
bash
FILTER='^\s*WARN auth: login failed user=\S+ ip=<HOST>
  

Anchor at both ends and allow no spaces in the user field (\S+), so a forged ip= can't slip in. The ^\s* is needed because fail2ban cuts the timestamp out of the line before matching, which leaves a leading space.

Exercise 7: The certificate curl rejects

Topics: Certificates, CSRs & a Private CA, Terminating TLS

The CA and Nginx are fine, yet curl refuses the connection. Inspect the certificate (openssl x509 -in api.crt -noout -ext subjectAltName,extendedKeyUsage), find the two mistakes in how it was signed, and fix them so the session prints api ok.

bash · try it yourself
openssl req -x509 -new -noenc -newkey ec -pkeyopt ec_paramgen_curve:P-256 -keyout ca.key -out ca.crt -days 365 -subj "/CN=Exercise CA" 2>/dev/null
openssl req -new -noenc -newkey ec -pkeyopt ec_paramgen_curve:P-256 -keyout api.key -out api.csr -subj "/CN=api.example.test" 2>/dev/null
openssl x509 -req -in api.csr -CA ca.crt -CAkey ca.key -set_serial 42 -days 30 -out api.crt \
  -extfile <(printf 'subjectAltName=DNS:api.example.com\nextendedKeyUsage=clientAuth\n') 2>/dev/null
printf 'pid nginx.pid;\nerror_log stderr;\nevents {}\nhttp { access_log off; server { listen 127.0.0.1:8443 ssl; ssl_certificate api.crt; ssl_certificate_key api.key; return 200 "api ok\\n"; } }\n' > nginx.conf
nginx -p "$PWD" -c nginx.conf -e stderr
for i in $(seq 50); do curl -sk https://127.0.0.1:8443/ > /dev/null && break; sleep 0.1; done
curl -sS --cacert ca.crt --resolve api.example.test:8443:127.0.0.1 https://api.example.test:8443/ 2>&1 | head -1
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null
curl: (60) SSL certificate problem: unsuitable certificate purpose

Expected output:

text
api ok
Show solution

The subjectAltName says api.example.com while clients connect to api.example.test, and the extended key usage allows only clientAuth, so even with the right name a strict client would reject it as a server certificate. Sign it with the right extensions:

bash
openssl x509 -req -in api.csr -CA ca.crt -CAkey ca.key -set_serial 42 -days 30 -out api.crt \
  -extfile <(printf 'subjectAltName=DNS:api.example.test\nextendedKeyUsage=serverAuth\n') 2>/dev/null

Exercise 8: Who is connected?

Topics: Listening Sockets: ss & ip

Write summarise(text, port) for saved ss -tan output: count the sockets on local port port per state, and count established connections per peer address. Print the states sorted by name and the two busiest peers.

python · try it yourself
SS = """\
State      Recv-Q Send-Q Local Address:Port   Peer Address:Port
LISTEN     0      511          0.0.0.0:443         0.0.0.0:*
LISTEN     0      128          0.0.0.0:22          0.0.0.0:*
ESTAB      0      0          10.0.1.21:443    203.0.113.7:51544
ESTAB      0      0          10.0.1.21:443    203.0.113.7:51546
ESTAB      0      0          10.0.1.21:443    198.51.100.4:40211
ESTAB      0      0          10.0.1.21:22     192.0.2.10:50022
TIME-WAIT  0      0          10.0.1.21:443    203.0.113.7:51530
TIME-WAIT  0      0          10.0.1.21:443    203.0.113.9:61001
SYN-RECV   0      0          10.0.1.21:443    203.0.113.66:40001
ESTAB      0      0          10.0.1.21:443    203.0.113.7:51550
"""

def summarise(text, port):
    states, peers = {}, {}
    # TODO: skip the header, split each line, keep lines whose local port is `port`,
    #       count states, and count ESTAB connections per peer IP
    return states, peers

states, peers = summarise(SS, 443)
print("states:", dict(sorted(states.items())))
print("top peers:", sorted(peers.items(), key=lambda kv: (-kv[1], kv[0]))[:2])
states: {}
top peers: []

Expected output:

text
states: {'ESTAB': 4, 'LISTEN': 1, 'SYN-RECV': 1, 'TIME-WAIT': 2}
top peers: [('203.0.113.7', 3), ('198.51.100.4', 1)]
Show solution
python
def summarise(text, port):
    states, peers = {}, {}
    for line in text.splitlines()[1:]:
        state, _, _, local, peer = line.split()
        if local.rsplit(":", 1)[1] != str(port):
            continue
        states[state] = states.get(state, 0) + 1
        if state == "ESTAB":
            ip = peer.rsplit(":", 1)[0]
            peers[ip] = peers.get(ip, 0) + 1
    return states, peers

rsplit(":", 1) splits at the last colon, so the same code works for IPv6 addresses such as [2001:db8::1]:443.

Test yourself

In Exercise 3, why does a drop-in named 10-hardening.conf win over 50-cloud-init.conf?

  1. Higher numbers are ignored
  2. Drop-ins are included in name order and, in sshd_config, the first value of a keyword wins
  3. sshd reads the newest file
  4. 10 is a special prefix

In Exercise 6, what does the $ anchor at the end of the filter prevent?

  1. Matching INFO lines
  2. An attacker appending a second ip= to fields they control, which a greedy pattern would take as the address to ban
  3. Matching IPv6
  4. Matching the timestamp