Skip to content

Nginx Apparmor

Now we'll create an apparmor profile for Nginx.

Let's first make sure we have all the apparmor profiles installed:

sudo -s
apt update && apt install apparmor-profiles apparmor-profiles-extra

First we'll amend a couple of abstraction files to add our custom certificate locations.

Edit the ssl_certs file:

nano /etc/apparmor.d/abstractions/ssl_certs

Add to this file:

  /etc/letsencrypt/*-certs/*/cert.pem r,
  /etc/letsencrypt/*-certs/*/chain.pem r,
  /etc/letsencrypt/*-certs/*/fullchain.pem r,

and now edit the ssl_keys file:

nano /etc/apparmor.d/abstractions/ssl_keys

Add to this file:

  /etc/letsencrypt/*-certs/*/*.pem r,

Now create a file for Nginx:

nano /etc/apparmor.d/usr.sbin.nginx

Enter the following:

#include <tunables/global>

/usr/sbin/nginx flags=(complain) {
  #include <abstractions/apache2-common>
  #include <abstractions/base>
  #include <abstractions/nameservice>
  #include <abstractions/openssl>
  #include <abstractions/ssl_keys>

  capability dac_override,
  capability dac_read_search,
  capability setgid,
  capability setuid,

  deny / rw,
  deny /bin/bash r,

  /usr/local/modsecurity/lib/lib*so* mr,
  /usr/sbin/nginx mr,
  /var/log/modsec_audit.log wk,
  /var/log/nginx/*.log w,
  owner /etc/nginx/bots.d/*.conf r,
  owner /etc/nginx/conf.d/ r,
  owner /etc/nginx/conf.d/*.conf r,
  owner /etc/nginx/custom-config/*.conf r,
  owner /etc/nginx/mime.types r,
  owner /etc/nginx/modsec/*.conf r,
  owner /etc/nginx/modsec/owasp-modsecurity-crs/ r,
  owner /etc/nginx/modsec/owasp-modsecurity-crs/**.conf r,
  owner /etc/nginx/modsec/owasp-modsecurity-crs/**.data r,
  owner /etc/nginx/modsec/owasp-modsecurity-crs/rules/ r,
  owner /etc/nginx/modsec/unicode.mapping r,
  owner /etc/nginx/nginx.conf r,
  owner /etc/nginx/sites-available/* r,
  owner /etc/nginx/sites-enabled/ r,
  owner /etc/nginx/uwsgi_params r,
  owner /run/nginx.pid rw,
  owner /usr/share/GeoIP/*.mmdb r,
  owner /var/cache/nginx/** rw,

}

Reload apparmor

service apparmor reload

Restart Nginx and browse one of your existing sites, then check for any further needed rules with:

aa-logprof

Repeat this process until aa-logprof finds no further rules.

Once you are happy with the profile, you can enforce it with:

aa-enforce usr.sbin.nginx