Php – SELinux restrict Apache/PHP access

hardeningPHPselinux

I installed a minimal CentOS system with Apache, PHP and SELinux in a default configuration:

SELinux status:                 enabled
SELinuxfs mount:                /sys/fs/selinux
SELinux root directory:         /etc/selinux
Loaded policy name:             targeted
Current mode:                   enforcing
Mode from config file:          enforcing
Policy MLS status:              enabled
Policy deny_unknown status:     allowed
Max kernel policy version:      29

If I want to change the Apache root directory, I must relabel this new directory otherwise SELinux block the access. But I found, with PHP scripts, that it's possible to do a lot more than I expected. For example, I can do the following actions without any alerts:

  • read /etc/passwd,
  • list /var/tmp,
  • display kernel version,
  • establish connection with external hosts

However I receive AVC alerts when I try to read attributes of /etc/shadow or when I try to access home directory.

First of all, is it normal? And how can I tweak SELinux to restrict more PHP actions?

I use CentOS 7 and my selinux-policy version is 3.13.1-23.el7_1.7.
(I also tried the same with Fedora and get the same results)

Best Answer

Everyone needs to be able to read /etc/passwd and write to /var/tmp. So these are not an issue.

The kernel version is not really an issue either, provided you're actually installing updates, using Ksplice, etc.

As for making outbound network connections, you can restrict this, as some web sites do not need to make such connections. But sometimes they do, for instance most web sites will need to connect to a database. You can manage this with SELinux booleans, such as:

# semanage boolean -l | grep httpd_can_network
httpd_can_network_relay        (off  ,  off)  Allow httpd to can network relay
httpd_can_network_connect_db   (off  ,  off)  Allow httpd to can network connect db
httpd_can_network_connect      (off  ,  off)  Allow httpd to can network connect
httpd_can_network_memcache     (off  ,  off)  Allow httpd to can network memcache
httpd_can_network_connect_cobbler (off  ,  off)  Allow httpd to can network connect cobbler

Setting httpd_can_network_connect allows all outbound network connections to anywhere; the others are more restrictive and only allow connecting to each specific service.


Also remember that if you are using nginx and php-fpm, that php is not restricted by SELinux until CentOS 6.6 and 7.