Restore a service SELinux is silently blocking

applied · 45 min · Objective 5.4

Task

Take a working service, move its files or change its port so SELinux blocks it, and restore it WITHOUT disabling SELinux. This is the single most common reason a service that "worked yesterday" stops after a move, and the single most common bad fix (setenforce 0) trades a working security control for a working service. Do it the right way and confirm the control is still enforcing.

Steps

  1. Confirm the baseline: the service serves content, getenforce says Enforcing, ls -Z shows the document root labelled httpd_sys_content_t.
  2. Break it the realistic way: move the document root to /srv/www (a fresh location inheriting the wrong context) and point the config there. Reload.
  3. Observe the failure honestly: the service starts, returns 403, and the log says nothing obvious. This is the trap -- the process is running, so it looks like a config error.
  4. Find the real cause: ausearch -m avc -ts recent shows the AVC denial naming the file and the context. Read ls -Z /srv/www: the label is wrong.
  5. Fix it correctly: add a file-context rule with semanage fcontext -a -t httpd_sys_content_t '/srv/www(/.*)?' then restorecon -Rv /srv/www. Explain why chcon alone would not survive a relabel.
  6. If the fault is a non-standard PORT instead, use semanage port -a -t http_port_t -p tcp 8090 and explain the difference from the file case.
  7. Confirm the service works AND getenforce still says Enforcing.

Verify

getenforce                              # must still say Enforcing
curl -s -o /dev/null -w '%{http_code}\n' http://localhost/   # 200, not 403
ls -Z /srv/www | head -3                # label is httpd_sys_content_t
ausearch -m avc -ts recent 2>/dev/null | tail -3   # no new denials after the fix

The two conditions must hold together: a 200 with getenforce reporting Enforcing is the whole point. A 200 after setenforce 0 is a failure disguised as a success -- it proves only that SELinux was the thing standing between the learner and the content, which was never in doubt.

Notes

chcon sets a label now; semanage fcontext records the rule that a relabel (restorecon, a filesystem relabel on reboot, a policy update) will reapply. Use chcon to test a hypothesis fast, semanage to make it stick. The lasting lesson is that a running-but-403 service is exactly the shape of an SELinux denial, and the log that says nothing is itself the clue to check the audit log instead.

This is an independent study companion for CompTIA Linux+ and is not produced by or endorsed by CompTIA.