Course contentsShow
← Linux
Lesson 965 of 1,8199. Security Hardening and Mandatory Access ControlFree lesson

Enforcing Changehat Restrictions

Implement dynamic profile switching within long-running applications for internal sub-process isolation.

In this lesson, you will learn how to implement granular security boundaries within a single, long-running application by leveraging AppArmor’s changehat feature to switch profiles dynamically.

Understanding Changehat

Standard AppArmor profiles wrap an entire application from start to finish. However, many server applications (like web servers or database proxies) perform tasks with varying levels of risk. Instead of running the whole process with the most permissive permissions needed by any of its sub-tasks, changehat allows the process to "drop" into a restricted "hat" (a sub-profile) when performing a specific, risky operation, and then return to the parent profile afterward.

The Mechanism

Think of a changehat as a temporary security "room" inside your application. When the application reaches a point where it needs to execute untrusted code or handle external requests, it signals the kernel to transition its execution context to a restricted sub-profile.

Consider a web server that spawns a helper to process a user-uploaded script. You don't want that script to have access to your database configuration files:

profile web-server /usr/sbin/httpd {
  # Standard web server rules
  /var/www/html/ r,

  # Define a "hat" for risky sub-processes
  ^script-handler {
    # Strictly limit access to only the sandbox directory
    /tmp/sandbox/ rw,
    deny /etc/ r,
  }
}

In your C or Python application, you would invoke the transition using a library call (like aa_change_hat in C). The application requests: "Enter the script-handler hat." The kernel immediately applies the strict restrictions defined in that block. Once the script finishes, the application calls aa_revert_hat to return to the broader web-server profile.

Why use this?

If an attacker exploits the sub-process while it is running in the script-handler hat, they are effectively trapped. They cannot break out to read your configuration files or modify system binaries because the kernel is actively enforcing the sub-profile's constraints, even though the parent process technically has those rights. This provides a vital layer of defense-in-depth, ensuring that a vulnerability in a small feature doesn't compromise the entire application.

Key Takeaway: Use changehat to isolate high-risk segments of your application into restricted sub-profiles, ensuring that a compromise in one task remains contained and cannot escalate to broader system access.