Linux Labs

Server security / Stage 7 of 10

A service with least privilege

Not running Starting usually ~20 s
Leave the lesson

Step 2 of 6 · on a machine · 8 min

Who the service runs as

The service read /etc/shadow because it ran as root. The first restriction is to change the user.

A unit file without a User= line is started by systemd as root: the process gets every power in the system. lab-preview only needs the reports directory, so you create a separate account with no login for it (sudo useradd -r -s /usr/sbin/nologin preview, useradd) and name it in the unit:

ini
[Service]
User=preview

You do not put this line in the package file under /usr/lib/systemd/system — an update overwrites it. You put it in a drop-in /etc/systemd/system/<unit>.d/<name>.conf, the way you raised a limit in the lesson on limits, and reload the settings: sudo systemctl daemon-reload, then sudo systemctl restart <unit>. The new process runs as the named user.

There is also a "for one run" option: DynamicUser=yes makes systemd create a temporary user for the lifetime of the service and remove it afterwards. Handy when the service does not need to own files on disk between runs.

Exercise · do it

Run lab-preview as preview

In a drop-in for lab-preview set its user to preview (the account already exists) so the change survives a package update, and hand the new process that user. Leave the unit file in /usr/lib/systemd/system as it is.

Sign in and start The machine is available after signing in

Goals · 0 of 2

  • Set User=preview in a drop-in on top of the package file not done yet
  • Restart the service as the new user not done yet

Step goals

0 of 2
  • Set User=preview in a drop-in on top of the package file — not done yet
  • Restart the service as the new user — not done yet
Ubuntu 24.04

Step goals

0 of 2
  • Set User=preview in a drop-in on top of the package file — not done yet
  • Restart the service as the new user — not done yet
Loading…