Course contentsShow
← Linux
Lesson 440 of 1,8194. Advanced Access Control ModelsFree lesson

Advanced Filesystem Hardening for Web Servers

Apply specific security contexts to web document roots to prevent unauthorized code execution.

In this lesson, you will learn how to restrict your web server's ability to execute code by applying granular security contexts to your document root directories.

The Problem: When Everything is Executable

By default, standard Linux permissions (UID/GID) are often too coarse for web applications. If your web server process (like www-data) has read/write access to your document root, a malicious script injected into an upload folder could potentially be executed by the web server, leading to a remote code execution (RCE) vulnerability. To mitigate this, we move beyond simple ownership and implement mandatory access controls that define exactly what can happen within specific directories.

Applying Security Contexts

The goal is to move to a "Least Privilege" filesystem model. For example, using SELinux, you can label your uploads directory differently than your scripts directory. Even if an attacker manages to upload a malicious PHP file to your uploads folder, the system policy will prevent the web server process from executing it because that folder lacks the httpd_sys_script_exec_t context.

Consider this workflow:

  1. Label the static content directory as read-only for the web process:
    semanage fcontext -a -t httpd_sys_content_t "/var/www/html/static(/.*)?"
    restorecon -Rv /var/www/html/static
    
  2. Isolate uploads so they cannot be interpreted as code:
    semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/html/uploads(/.*)?"
    restorecon -Rv /var/www/html/uploads
    

By assigning these specific contexts, you create a "sandbox" within your filesystem. The web server process will only be permitted to execute files labeled as scripts (httpd_sys_script_exec_t) and will be explicitly blocked from running anything inside the uploads directory, even if the file permissions are set to 777. This decoupling of "file access" from "execution capability" is a cornerstone of modern web server hardening, ensuring that even if a directory is writable by the application, it remains non-executable for the underlying system.

Key Takeaway: By applying specific security contexts (like SELinux labels) to your document root, you can prevent the web server from executing malicious code even if an attacker gains write access to your directories.