SELinux安全子系统
SELinux(Security-Enhanced Linux)是美国国家安全局在Linux开源社区的帮助下开发的一个强制访问控制(MAC,Mandatory Access Control)的安全子系统。使用SELinux技术的目的是为了让各个服务进程都受到约束,使其仅获取到本应获取的资源。
SELinux服务有三种运行模式:
- enforcing:强制启用安全策略模式,将拦截服务的不合法请求。
- permissive:遇到服务越权访问时,只发出警告而不强制拦截,并记录日志
- disabled:对于越权的行为不警告也不拦截,完全关闭SELinux
可以通过修改配置文件 /etc/selinux/config 来更改SELinux的默认运行模式,但不会立即生效(重启生效)。
[root@redhat ~]# vim /etc/selinux/config
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=enforcing
# SELINUXTYPE= can take one of these three values:
# targeted - Targeted processes are protected,
# minimum - Modification of targeted policy. Only selected processes are protected.
# mls - Multi Level Security protection.
SELINUXTYPE=targeted
可以通过getenforce获取SELinux当前运行模式或setforce [ 0|1 ] 修改当前运行模式(0=enforcing\1=permissive,临时修改,重启失效)。
[root@redhat ~]# getenforce
Enforcing
[root@redhat ~]# setenforce 0
[root@redhat ~]# getenforce
Permissive
SELinux两种应用:
- SELinux域 - 对服务的功能进行限制
- SELinux安全上下文 - 使文件资源只能被特定服务访问
使用ls命令加 -Z 参数可以查看文件的SELinux安全上下文值
[root@redhat ~]# ls -lZd /var/www/html/
drwxr-xr-x. 2 root root system_u:object_r:httpd_sys_content_t:s0 6 Feb 6 2019 /var/www/html/
在文件上设置的SELinux安全上下文是由用户段、角色段以及类型段等多个信息项共同组成的。其中,用户段system_u代表系统进程的身份,角色段object_r代表文件目录的角色,类型段httpd_sys_content_t代表网站服务的系统文件。
使用semanage命令查询与修改SELinux默认目录的安全上下文:
- -l参数用于查询
- -a参数用于添加
- -m参数用于修改
- -d参数用于删除
- -t 修改的类型
[root@linuxprobe ~]# semanage fcontext -a -t httpd_sys_content_t /home/wwwroot
[root@linuxprobe ~]# semanage fcontext -a -t httpd_sys_content_t /home/wwwroot/*
还需要使用restorecon命令将设置好的SELinux安全上下文立即生效。
[root@linuxprobe ~]# restorecon -Rv /home/wwwroot/
restorecon reset /home/wwwroot context unconfined_u:object_r:home_root_t:s0->unconfined_u:object_r:httpd_sys_content_t:s0
restorecon reset /home/wwwroot/index.html context unconfined_u:object_r:home_root_t:s0->unconfined_u:object_r:httpd_sys_content_t:s0
使用getsebool获取或setsebool修改SELinux域安全策略规则:
[root@redhat ~]# getsebool -a | grep httpd_enable
# -a参数查看全部
httpd_enable_cgi --> on
httpd_enable_ftp_server --> off
httpd_enable_homedirs --> off
[root@redhat ~]# setsebool -P httpd_enable_homedirs=on
#加-P参数永久和立即生效