请尝试接纳SELinux

来源:互联网 发布:广州新页进销存软件 编辑:程序博客网 时间:2024/05/08 23:34

请尝试接纳SELinux

SELinux常被认为是麻烦之源,相信大家都敲过这样的代码来狠狠把它给关掉:SELINUX=disable或者setenforce 0,其实只要理解清楚了SELinux,相信这些所谓的“麻烦”都不是问题。

 

SELinux的工作模式

SELinux有一下3种工作模式:Disabled、Permissive、Enforcing,可以通过修改/etc/selinux/config文件来永久切换工作模式,也可以使用命令setenforce来暂时切换工作模式。

 

1.Disabled模式

不使用SELinux的状态,不输出监视日志并可以自由访问资源。

 

2.Permissive模式

不对资源的访问进行控制,但会把违反条约的访问记录到日志中。

 

3.Enforcing模式

对资源的访问进行控制,阻拦所有违反条约的操作。

 

出现“麻烦”

我们可以试一下Apache,首先在网页根目录/var/www/html下生成index.html文件,添加以下内容——hogehoge

# cd /var/www/html# vi index.html# cat index.htmlhogehoge

然后,通过浏览器或者curl工具访问该文件:

# curl http://localhost/hogehoge

接着,我们新建一个文件/tmp/index.html并把它复制到/var/www/html中。

# vi /tmp/index.html# cat /tmp/index.htmlfoobar# 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.htmlon this server.</p></body></html>

 

为什么会出现“麻烦”?

我们可以查看监视日志文件:

# ausearch -m avc(省略中间的内容)time->Wed Dec 21 08:41:26 2016type=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/htmldrwxr-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

Apache(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/htmldrwxr-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/htmldrwxr-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
原创粉丝点击