SELinux常被认为是麻烦之源,相信大家都敲过这样的代码来狠狠把它给关掉:SELINUX=disable或者setenforce 0,其实只要理解清楚了SELinux,相信这些所谓的“麻烦”都不是问题。
SELinux有一下3种工作模式:Disabled、Permissive、Enforcing,可以通过修改/etc/selinux/config文件来永久切换工作模式,也可以使用命令setenforce来暂时切换工作模式。
不使用SELinux的状态,不输出监视日志并可以自由访问资源。
不对资源的访问进行控制,但会把违反条约的访问记录到日志中。
对资源的访问进行控制,阻拦所有违反条约的操作。
我们可以试一下Apache,首先在网页根目录/var/www/html下生成index.html文件,添加以下内容——hogehoge。
# cd /var/www/html # vi index.html # cat index.html hogehoge然后,通过浏览器或者curl工具访问该文件:
# curl http://localhost/ hogehoge接着,我们新建一个文件/tmp/index.html并把它复制到/var/www/html中。
# vi /tmp/index.html # cat /tmp/index.html foobar # cp -a /tmp/index.html /var/www/html/ cp: 把文件`/var/www/html/index.html'给覆盖掉之后,我们再访问该文件,发现403报错:
# curl http://localhost/ <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>403 Forbidden</title> </head><body> <h1>Forbidden</h1> <p>You don't have permission to access /index.html on this server.</p> </body></html>我们可以查看监视日志文件:
# ausearch -m avc (省略中间的内容) time->Wed Dec 21 08:41:26 2016 type=SYSCALL msg=audit(1482277286.335:911): arch=c000003e syscall=2 success=no exit=-13 a0=7f7c21930280 a1=80000 a2=0 a3=4 items=0 ppid=2385 pid=2390 auid=4294967295 uid=48 gid=48 euid=48 suid=48 fsuid=48 egid=48 sgid=48 fsgid=48 tty=(none) ses=4294967295 comm="httpd" exe="/usr/sbin/httpd" subj=system_u:system_r:httpd_t:s0 key=(null) type=AVC msg=audit(1482277286.335:911): avc: denied { open } for pid=2390 comm="httpd" path="/var/www/html/index.html" dev="dm-0" ino=416303 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:user_tmp_t:s0 tclass=file从上面可以看出是在system_u:system_r:httpd_t环境下访问不到unconfined_u:object_r:user_tmp_t这个文件。
# ls -laZ /var/www/html drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 . drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 .. -rw-r--r--. root root unconfined_u:object_r:user_tmp_t:s0 index.htmlApache(httpd)对于/var/www/*目录下的允许公开访问的文件必须赋予httpd_sys_content_t权限。
# grep -R '/var/www' /etc/selinux/targeted/ (省略中间的内容) /etc/selinux/targeted/active/file_contexts:/var/www(/.*)? system_u:object_r:httpd_sys_content_t:s0当然可以使用chcon来设置个别文件,但是对于/var/www这种特定的目录,我们可以使用系统为我们准备好的标准模板。这种情况下,使用restorecon命令来简单地更正文件的属性。
# ls -alZ /var/www/html drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 . drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 .. -rw-r--r--. root root unconfined_u:object_r:user_tmp_t:s0 index.html # restorecon -RF /var/www/html/ # ls -alZ /var/www/html drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 . drwxr-xr-x. root root system_u:object_r:httpd_sys_content_t:s0 .. -rw-r--r--. root root system_u:object_r:httpd_sys_content_t:s0 index.html现在应该就能正常访问到网页了。
# curl http://localhost/ foobar