Friday, October 15, 2010

Playing with SELinux

Recently on a fresh installation of CentOS 5, I was setting up mysql. My troubles started after changing mysql's datadir from the default(/var/lib/mysql) to /db in /etc/my.cnf

All attempts of starting mysqld failed. A quick look in mysql's log showed complaints about Err no. 13.  This was clearly an issue of file permissions. Even chmod / chown could not help. I could not start mysqld.

 However, If I changed the datadir back to the default (/var/lib/mysql), things worked just fine.

My next guess was SELinux. To confirm, I used the following command
# sestatus
And yes, indeed, it was SELinux's doing. SElinux was enabled and enforcing.
Here I stood with 2 choices (and yes, I experimented with both approaches),
  • Disable SELinux and avoid all the headache
  • Change things to work with SELinux


Disable SELinux and avoid all the headache
I just had to edit the config file for SELinux, and change it's value to disabled.
# vi /etc/sysconfig/selinux
However, a reboot was required before the changes were applied.

Change things to work with SELinux
The approach I took was quite straight forward. I looked at what worked and applied the same settings on my new datadir.

When I looked at the SELinux security context on /var/lib/mysql , it showed something like,
# ls -lZ /var/lib/mysql
drwx------  mysql mysql system_u:object_r:mysqld_db_t    mysql
drwx------  mysql mysql system_u:object_r:mysqld_db_t    test
.....
.....

Now I simply applied the same on /db , like so
# chcon -Rv --type=mysqld_db_t -u system_u -r object_r /db
Thats it. SELinux had no more problems with mysqld using the new datadir.


A Complete tutorial on SELinux / CentOS can be found at http://wiki.centos.org/HowTos/SELinux