红联Linux门户
Linux帮助

启用SELinux时遇到的问题

发布时间:2014-11-06 15:54:14来源:linux网站作者:firefoxbug

一台CentOS5.7的机器,原来只是在公司内部访问,SELinux是禁用的状态,现需要搭建成FTP服务器并发布到外网上去,为了安全,启用SELinux。编辑/etc/selinux/config文件,将SELINUX=disabled改为SELINUX=permissive,保存后重启系统。(SELinux从禁用状态转变为启用时,需要重启系统以重新标记文件的上下文,红帽建议先将SELinux的值设置为permissive,重新标记完成后再设置为enforcing。)


按道理说,重新对整个文件系统进行标记应该是比较费时间的,至少需要几分钟,但在这台机器上敲入reboot命令后,发现它很快就启动起来的。登录后使用命令getenforce,返回permissive,说明SELinux的状态正常,于是把SELinux的状态设置为Enforcing,设置完成后重启了一下vsftpd和httpd服务,这下问题大了,服务无法正常启动,提示“errorwhile loading shared libraries: libssl.so.6: failed to map segment from sharedobject: Permission denied”,直觉告诉我是因为重启时没有对整个文件系统进行正确的relabeling引起的,于是执行命令touch   /.autorelabel   ,在/下创建一个.autorelabel文件,有这个文件存在,系统在重启时就会对整个文件系统进行relabeling,但奇怪的是重启又很快完成,看来还是没有完成relabeling。


最后google了一下,发现一个解决方案,执行下面三条命令:

fixfiles    -f   relabel

touch   /.autorelabel

reboot


但在执行第一条命令时就报错,提示“/etc/selinux/targeted/contexts/files/file_contexts.homedirs: line 18 hasinvalid context user_u:object_r:user_mozilla_home_t:s0”,报错信息有多条类似的,不止这一条。

再次搜索,最后在红帽的网站上找到了原因,之所以会出现这个问题因为在SELinux是disabled的状态下升级了操作系统,参见https://bugzilla.redhat.com/show_bug.cgi?id=449420


解决方法:

在启用SELinux并重启后,执行下列命令:

genhomedircon

touch /.autorelabel

reboot


这次在重启的时候就停在relabeling的地方,大概花了5分钟左右,完成后进入系统,将SELinux设置为Enforcing模式,执行命令ps  -eZ  查看进程的SELinux上下文,一切正常。

附:

系统启动时,运行/etc/rc.d/rc.sysinit脚本,在这个脚本中判断了/.autorelabel文件是否存在,如果存在,则会调用fixfiles命令对整个文件系统进行relabeling。


相关代码如下:

If   [ -f /.autorelabel ] || strstr"$cmdline" autorelabel ; then
relabel_selinux
fi
relabel_selinux() {
if [ -x/usr/bin/rhgb-client ] && /usr/bin/rhgb-client --ping ; then
chvt 1
fi
# if /sbin/init isnot labeled correctly this process is running in the
# wrong context,so a reboot will be reuired after relabel
REBOOTFLAG=`restorecon -v /sbin/init`
AUTORELABEL=
./etc/selinux/config
if ["$AUTORELABEL" = "0" ]; then
rm -f  /.autorelabel
echo
echo$"*** Warning -- SELinux ${SELINUXTYPE} policy relabel is required. "
echo $"*** /etc/selinux/configindicates you want to manually fix labeling"
echo$"*** problems. Dropping you to a shell; the system will reboot"
echo$"*** when you leave the shell."
echo"0" > $selinuxfs/enforce
sulogin
echo$"Unmounting file systems"
umount -a
mount -n -oremount,ro /
echo$"Automatic reboot in progress."
reboot -f
else
echo
echo$"*** Warning -- SELinux ${SELINUXTYPE} policy relabel is required."
echo$"*** Relabeling could take a very long time, depending on file"
echo$"*** system size and speed of hard drives."
echo"0" > $selinuxfs/enforce
/sbin/fixfiles  restore > /dev/null 2>&1
rm -f  /.autorelabel
if [ ! -z "$REBOOTFLAG" ]; then
echo$"Automatic reboot in progress."
reboot -f
fi
echo$SELINUX_STATE > $selinuxfs/enforce
if [ -x/usr/bin/rhgb-client ] && /usr/bin/rhgb-client --ping ; then
chvt 8
fi
fi
}