Skip to content

Apache Apparmor

Now we'll create an apparmor profile for the Apache2 process

First we'll amend a couple of abstraction and tunables files.

Edit the php file:

nano /etc/apparmor.d/abstractions/php

Add to this file:

  /usr/share/php{,7.4}-*/ r,
  /usr/share/php{,7.4}-*/** mr,

and now create a run file in the tunables directory:

nano /etc/apparmor.d/tunables/run

Add to this file:

@{run}=/run/ /var/run/

Edit the global tunables file:

nano /etc/apparmor.d/tunables/global

and add the following line:

#include <tunables/run>

Install the apparmor mod for Apache2:

apt update && apt install libapache2-mod-apparmor

and enable it:

a2enmod apparmor

Now we need to create sub profiles for each of our Apache2 virtual hosts.

First is PHPMyAdmin:

nano /etc/apparmor.d/apache2.d/phpmyadmin-a2

Enter the following:

  ^phpmyadmin-a2 flags=(attach_disconnected) {
    #include <abstractions/apache2-common>
    #include <abstractions/base>
    #include <abstractions/nameservice>
    #include <abstractions/php>

    capability setuid,
    capability setgid,

    # for log writing (could be abstracted)
    /var/log/apache2/access.log w,
    /var/log/apache2/error.log w,

    # Socket access
    /run/php/php7.4-fpm-www-phpmyadmin.sock wr,

    # Access to standard PHPMyAdmin files
    /usr/share/phpmyadmin/** r,

    # Deny access to these locations
    deny /usr/share/phpmyadmin/templates/** r,
    deny /usr/share/phpmyadmin/libraries/** r,
    deny /usr/share/phpmyadmin/setup/** r,
    deny /usr/share/phpmyadmin/examples/** r,
    deny /usr/share/phpmyadmin/{Changelog,LICENSE,README,RELEASE-DATE-*,CONTRIBUTING.md,composer.*} r,
    deny /usr/share/phpmyadmin/*.php r,
    deny /usr/share/phpmyadmin/**/*.php r,
    deny /var/www/** r,

    # Deny access to Bash
    deny /bin/bash r,
    deny /bin/dash r,
 }

Now open up the PHPMyAdmin virtualhost:

nano /etc/apache2/sites-available/pma2.example.com.conf

Add the following directive inside the virtualhost before the first directory block:

    <IfModule mod_apparmor.c>
        AADefaultHatName phpmyadmin-a2
    </IfModule>

Repeat this process with any other virtualhosts you wish to add further protection to.

Reload Apparmor and put the Apache profile into complain mode:

service apparmor reload
aa-complain usr.sbin.apache2

Restart Apache2

service apache2 restart

Try logging into PHPMyAdmin

Run aa-logprof to pick up any other rules to be added to the profile.

Once you're happy with everything, you can enforce the profile with:

aa-enforce usr.sbin.apache2