Managing Data Directory Permissions with SELinux and AppArmor

Managing MariaDB Data Directory Permissions with SELinux and AppArmor

Understanding the Problem

When you move MariaDB's data directory (usually /var/lib/mysql or /var/lib/mariadb), the MariaDB server process needs permission to read and write to the new location. SELinux and AppArmor enforce mandatory access control, meaning that even if the MariaDB user has file system permissions, these security modules can still block access.

Identifying Your Security Module

First, determine which security module your system uses:

  • SELinux: Run getenforce. If it returns Enforcing or Permissive, SELinux is active

  • AppArmor: Run apparmor_status. If it shows loaded profiles, AppArmor is active

Configuring SELinux

If SELinux is active, follow these steps:

  1. Identify the Current SELinux Context of the Data Directory:

    ls -ldZ /var/lib/mysql  # Or /var/lib/mariadb, depending on your system

    The output will look something like this:

    drwxr-xr-x. mysql mysql system_u:object_r:mysqld_db_t:s0 /var/lib/mysql

    or

    drwxr-xr-x. mysql mysql system_u:object_r:mariadb_db_t:s0 /var/lib/mariadb
  2. Apply the Correct SELinux Context:

    # If using mysqld_db_t
    semanage fcontext -a -t mysqld_db_t "/new/path/to/mariadb_data(/.*)?"
    # OR
    # If using mariadb_db_t
    semanage fcontext -a -t mariadb_db_t "/new/path/to/mariadb_data(/.*)?"
    
    restorecon -Rv /new/path/to/mariadb_data
  3. Update MariaDB Configuration: Edit the MariaDB configuration file (usually /etc/my.cnf, /etc/mysql/my.cnf, or /etc/my.cnf.d/server.cnf):

    [mariadb] # or [mysqld] depending on your config file
    datadir=/new/path/to/mariadb_data
  4. Restart MariaDB:

    systemctl restart mariadb

Troubleshooting SELinux

  • Check SELinux Logs: ausearch -m avc -ts recent to show denied operations

  • Set SELinux to Permissive (Testing Only): setenforce 0 and setenforce 1 to revert

Configuring AppArmor

  1. Edit the AppArmor Profile:

    # Create backup
    cp /etc/apparmor.d/usr.sbin.mariadbd /etc/apparmor.d/usr.sbin.mariadbd.bak

    Edit the profile and add new rules:

    /new/path/to/mariadb_data/ r,
    /new/path/to/mariadb_data/** rwk,
  2. Reload the AppArmor Profile:

    systemctl reload apparmor
  3. Update MariaDB Configuration:

    [mariadb] # Or [mysqld]
    datadir=/new/path/to/mariadb_data
  4. Restart MariaDB:

    systemctl restart mariadb

Troubleshooting AppArmor

  • Check Logs: Use dmesg | grep apparmor or check /var/log/syslog or /var/log/audit/audit.log

  • Complain Mode (Testing Only):

    aa-complain /usr/sbin/mariadbd  # or /usr/sbin/mysqld
    aa-enforce /usr/sbin/mariadbd   # to revert

Last updated

Was this helpful?