Linux Services and Logs
On a server, almost nothing runs because a person typed a command. The web server, the database, the SSH daemon, the backup timer: all of them are services started by systemd at boot, and each one runs with some identity and some set of privileges. When an attacker breaks into a server, they nearly always arrive through a service (a vulnerable web app, an exposed SSH port), and they nearly always leave traces in the logs. So two questions decide how bad a break-in gets and whether anyone notices: what could the compromised service do? and did the logs record it?
This lesson answers both from the defender's side. Unit files, systemctl and journalctl are taught in Services and journalctl; here you read them for security.
Services: identity and blast radius
A service's unit file says who it runs as and what the kernel lets it touch. A web app that runs as root and gets compromised hands the attacker root; the same app as User=lab-app with a read-only file system hands them one unprivileged account in a box.
| Unit setting | Security meaning |
|---|---|
User=, Group=, DynamicUser=yes |
the identity; anything but root is the first win |
NoNewPrivileges=yes |
SUID programs and file capabilities can't raise privileges inside the service |
ProtectSystem=strict, ReadWritePaths= |
the whole file system is read-only except the listed paths |
ProtectHome=yes, PrivateTmp=yes |
no access to users' homes; a private /tmp |
CapabilityBoundingSet=, AmbientCapabilities= |
which root powers (if any) the service may hold, e.g. only CAP_NET_BIND_SERVICE |
RestrictAddressFamilies=, SystemCallFilter= |
which socket types and system calls are allowed (seccomp) |
On a host, systemd-analyze security <unit> scores these settings for one service, and Service Sandboxing shows each in action. The session below does the auditor's quick version: it reads three unit files (written into the sandbox, since the sandbox has no systemd) and reports the most important gaps.
mkdir units
cat > units/lab-app.service <<'EOF'
[Service]
ExecStart=/opt/lab-app/bin/server
User=lab-app
NoNewPrivileges=yes
ProtectSystem=strict
ReadWritePaths=/var/lib/lab-app
PrivateTmp=yes
EOF
cat > units/old-report.service <<'EOF'
[Service]
ExecStart=/opt/report/report.sh
EOF
cat > units/metrics.service <<'EOF'
[Service]
ExecStart=/usr/local/bin/metrics --listen 0.0.0.0:9100
User=root
EOF
for f in units/*.service; do
issues=""
user=$(sed -n 's/^User=//p' "$f")
[ -z "$user" ] || [ "$user" = root ] && issues="$issues runs-as-root"
grep -q '^NoNewPrivileges=yes' "$f" || issues="$issues no-NoNewPrivileges"
grep -q '^ProtectSystem=' "$f" || issues="$issues writable-system"
grep -q '0\.0\.0\.0' "$f" && issues="$issues listens-on-all-interfaces"
printf '%-22s %s\n' "$(basename "$f")" "${issues:- ok}"
donelab-app.service ok
metrics.service runs-as-root no-NoNewPrivileges writable-system listens-on-all-interfaces
old-report.service runs-as-root no-NoNewPrivileges writable-system
old-report.service has no User= at all, so systemd starts it as root, the default for system services. That's the quiet case auditors find most often: nobody chose root, it simply wasn't changed.
Logs: where the evidence is
Linux writes security events in two places, often both:
- The journal (systemd-journald, read with
journalctl), structured, with fields such as_SYSTEMD_UNIT,_UID,_PID.journalctl -u ssh,journalctl _COMM=sudo,journalctl -p warning --since today. - Text files written by rsyslog: on Debian and Ubuntu
/var/log/auth.log(logins, sudo, PAM, user management) and/var/log/syslog; on RHEL-family systems/var/log/secureand/var/log/messages. - The audit log (
auditd,/var/log/audit/audit.log) for kernel-level events you ask for: "every write to/etc/sudoers", "everyexecveby UID 0".
What an analyst looks for in the authentication log:
| Event | Example line (shortened) | Why |
|---|---|---|
| failed SSH password | sshd[…]: Failed password for alice from 10.10.0.66 |
brute force, spraying |
| login for a user that doesn't exist | Invalid user oracle from 10.10.0.66 |
username guessing |
| successful login | Accepted publickey for bob from 10.10.0.5 |
who got in, how, from where |
| sudo use | sudo: bob : … USER=root ; COMMAND=/usr/bin/id |
privilege use |
| account changes | useradd[…]: new user: name=support2 |
persistence, a new backdoor account |
Reading a synthetic auth log
The session writes a small, made-up auth.log from the lab network (10.10.0.0/24, host srv01) and asks the questions an analyst asks first. Real logs have thousands of lines; the commands are the same.
cat > auth.log <<'EOF'
Jan 15 10:00:01 srv01 sshd[811]: Accepted publickey for bob from 10.10.0.5 port 50110 ssh2
Jan 15 10:02:11 srv01 sshd[820]: Failed password for alice from 10.10.0.66 port 41001 ssh2
Jan 15 10:02:13 srv01 sshd[820]: Failed password for alice from 10.10.0.66 port 41001 ssh2
Jan 15 10:02:15 srv01 sshd[822]: Invalid user oracle from 10.10.0.66 port 41003
Jan 15 10:02:16 srv01 sshd[822]: Failed password for invalid user oracle from 10.10.0.66 port 41003 ssh2
Jan 15 10:02:18 srv01 sshd[824]: Failed password for bob from 10.10.0.66 port 41005 ssh2
Jan 15 10:02:20 srv01 sshd[826]: Failed password for carol from 10.10.0.66 port 41007 ssh2
Jan 15 10:02:22 srv01 sshd[828]: Accepted password for carol from 10.10.0.66 port 41009 ssh2
Jan 15 10:03:05 srv01 sudo: carol : TTY=pts/1 ; PWD=/home/carol ; USER=root ; COMMAND=/usr/bin/bash
Jan 15 10:03:40 srv01 useradd[901]: new user: name=support2, UID=1005, GID=1005, home=/home/support2, shell=/bin/bash, from=/dev/pts/1
Jan 15 10:04:02 srv01 sudo: bob : TTY=pts/0 ; PWD=/home/bob ; USER=root ; COMMAND=/usr/bin/systemctl restart lab-app.service
EOF
echo '== failed logins per source'
grep -E 'Failed password' auth.log | grep -oE 'from [0-9.]+' | sort | uniq -c
echo '== accounts tried from 10.10.0.66'
grep 'from 10.10.0.66' auth.log | grep -oE 'for (invalid user )?[a-z0-9]+' | awk '{print $NF}' | sort -u | tr '\n' ' '; echo
echo '== successful logins'
awk '/Accepted/ {print $3, $9, $11, "("$7")"}' auth.log
echo '== root commands via sudo'
grep -E 'sudo: .*USER=root' auth.log | sed -E 's/.*sudo: +([a-z]+) .*COMMAND=(.*)/\1 -> \2/'
echo '== new accounts'
grep -oE 'new user: name=[a-z0-9]+' auth.log== failed logins per source
5 from 10.10.0.66
== accounts tried from 10.10.0.66
alice bob carol oracle
== successful logins
10:00:01 bob 10.10.0.5 (publickey)
10:02:22 carol 10.10.0.66 (password)
== root commands via sudo
carol -> /usr/bin/bash
bob -> /usr/bin/systemctl restart lab-app.service
== new accounts
new user: name=support2
Read together, the five answers tell a story in two minutes: one source, 10.10.0.66, failed five times across four accounts within ten seconds, one or two tries per account (password spraying, see Brute Force and Password Spraying), got in as carol by password, opened a root shell with sudo 43 seconds later and created an account. bob's own login and sudo use look routine. That's the pattern a SIEM rule encodes (Defensive Security): failures followed by a success from the same source, then privilege use, then a new account.
How it is detected
- Collect logs off the host (rsyslog forwarding, the journal's remote upload, or an agent) so an attacker who becomes root can't simply delete them; a sudden gap or a shrinking log file is itself an alert.
- Rules on the events above: failures per source per minute, a success after many failures, sudo to a shell (
COMMAND=/usr/bin/bash), new users and group changes, edits to sudoers and SSH keys (audit rules such as-w /etc/sudoers -p wa -k sudoers). - Baseline services: the list of enabled units and listening ports (
systemctl list-unit-files --state=enabled,ss -tlnp) compared every day; a new service is a common way to stay on a machine.
How it is fixed or prevented
- Every service gets its own user and the sandboxing settings above; nothing listens on
0.0.0.0unless it must. - SSH: keys only (
PasswordAuthentication no), no root login, and rate limiting (SSH hardening, fail2ban). - Logs: forwarded, kept long enough (weeks to months, as your policy says), rotated without losing them (logrotate), and readable only by admins (
/var/log/auth.logis640 syslog:admon Ubuntu). - Clocks synchronised (NTP), or correlating events across hosts becomes guesswork.
Pitfalls
- Grepping only
Failed passwordmissesInvalid userlines and attacks on keys; look at successes too, they are what matters. - Trusting the host's own log after a compromise. Root can edit it; the forwarded copy is the evidence.
- Logging secrets. A debug log with request bodies records passwords; that log then needs the same protection as the password database.
- Too many alerts. A rule that fires on every single failure is ignored within a week; count, group and threshold.
Practice
- In the session's log, how many seconds passed between
carol's successful login and the root shell? - Write a
grepthat lists only lines where a user ran a shell or an interpreter through sudo. - Which two settings would you add first to
old-report.service?
Answers
- 43 seconds (10:02:22 to 10:03:05).
grep -E 'sudo:.*COMMAND=/usr/bin/(bash|sh|zsh|python3|perl)( |$)' auth.log.User=with a dedicated account (e.g.User=report, orDynamicUser=yes), andNoNewPrivileges=yeswithProtectSystem=strictplus the oneReadWritePaths=the report needs.
Test yourself
A unit file has ExecStart= but no User= line. Which user runs the service?
- nobody
- the user who enabled it
- root
- a random dynamic user
Which file holds SSH logins and sudo use on Ubuntu?
/var/log/auth.log/var/log/kern.log/etc/shadow/var/log/dpkg.log
One source fails on four different accounts, then succeeds on one. What is it most likely?
- A user who forgot their password
- Password spraying that found a weak password
- A DNS problem
- A log rotation
Why forward logs to another machine?
- To save disk space
- An attacker who becomes root on the host can change or delete the local copy
- journald cannot store logs
- To make them public