Centos – SELinux: Letting Apache talk to MySQL on CentOS

apache-2.2centosMySQLselinux

So I have chrooted MySQL into /opt/chroot/mysql, and everything runs fine. Apache is configured normally, and also runs fine.

I created a small PHP script which connects to the MySQL Daemon, and configured PHP so that the default socket used is the chrooted one. When SELinux is disabled, the script is able to connect fine. However, when SELinux is enabled, the script fails to connect (with error number 13), and the audit log tells me that SELinux denied the request.

Every tutorial I've found that deals with this problem tells me to disable SELinux. This is not what I want to do, so please don't suggest it! I want a solution that works whilst SELinux is enabled…I assume one must exist…

I'd guess that I probably have to change the SELinux contexts for the mysql files, but I'm not sure what to change them into to make it work.

Best Answer

UPDATE 2

type=AVC msg=audit(1318863312.959:435): avc: denied { connectto } for pid=12472 comm="httpd" path="/opt/chroot/mysql/var/lib/mysql/mysql.sock" scontext=unconfined_u:system_r:httpd_t:s0 tcontext=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 tclass=unix_stream_socket

You can build the custom SELinux policy module by following steps:

# grep httpd_t audit.log | audit2allow -m httpd > httpd.te
# checkmodule -M -m -o httpd.mod httpd.te
# semodule_package -m httpd.mod -o httpd.pp 
# semodule -i httpd.pp

Refer to this topic for more details.


UPDATE

  1. Run semanage command to add a context mapping for /opt/chroot/mysql/var/lib/mysql/:

    # semanage fcontext -a -t mysqld_db_t "/opt/chroot/mysql/var/lib/mysql(/.*)?"
    
  2. And use restorecon command to apply this context mapping:

    # restorecon -Rv /opt/chroot/mysql/var/lib/mysql
    

If you are connecting via TCP/IP, try this:

# setsebool -P httpd_can_network_connect 1