In this lesson, you will learn how to configure file context mapping to ensure your SELinux security labels persist correctly even after system updates or file relocations.
Understanding Context Persistence
When you manually apply a security context to a file using chcon, you are performing a temporary change. If the system relabels the filesystem—such as during an OS update or an autorelabel process—those manual changes are overwritten by the system's default policy. To make security labels permanent, we don't just change the label; we define a mapping rule that the system refers to whenever it needs to "reset" its security state.
Using semanage fcontext
The tool semanage fcontext is used to add, modify, or delete the rules that define what the security context of a file should be. By adding a rule to the system’s configuration database, you ensure that even if you move files or perform a major system upgrade, the policy engine knows exactly how to label them.
For example, if you have a custom web directory at /srv/my_web_data, you must tell SELinux that this location should behave like standard web content:
# Add the mapping rule for the directory and its contents
sudo semanage fcontext -a -t httpd_sys_content_t "/srv/my_web_data(/.*)?"
# Apply the mapping to the filesystem
sudo restorecon -Rv /srv/my_web_data
In the example above, the -a flag adds the record, and -t defines the target type (httpd_sys_content_t). The regex (/.*)? ensures that the rule applies to the directory and everything inside it. The restorecon command then forces the filesystem to match these mapped definitions.
Why This Matters
If you skip this step, your service might stop working after a security update or a disk maintenance task because the files lost their required security labels. By maintaining a mapping, you integrate your custom configuration directly into the system's "Root of Trust," ensuring that your security posture remains resilient regardless of how often the system reconfigures itself.
Key Takeaway: Use semanage fcontext to create persistent mapping rules so that file labels survive system-wide relabeling and updates.