一、故障类型

二、配置文件、目录介绍

三、原理介绍

四、命令参考

官网URL:http://wiki.centos.org/HowTos/SELinux

一、故障类型

1.        relabeling 文件

使用chcon命令来修改文件的安全性文本

不适用:如果整个文件系统relabel,那么用此命令进行的设置将失效,除非使用semanage修改默认策略(Modifying security contexts in this manner will persist between reboots unless the complete filesystem is relabeled (see later). To make the security context changes permanent, even through a complete filesystem relabel, we can use the SELinux Management Tool or the ‘semanage’ command from the command line)。

2.        恢复单个或多个默认安全性文本

使用restorecon命令

3.        允许绑定/侦听某个端口

By default, the SELinux policy will only allow services access to recognized ports associated with those services. If we wanted to allow Apache to listen on tcp port 81, we can add a rule to allow that using the ‘semanage’ command:

# semanage port -a -t http_port_t -p tcp 81

# semanage port –l(A full list of ports that services are permitted access by SELinux can be obtained with: )

4.        修改布尔值方式

getsebool、setsebool(getsebool -a or getsebool boolean… || setsebool [ -P ] boolean value | bool1=val1 bool2=val2…):

Minor modifications to SELinux policies can be made without modifying and recompiling the policy source by setting boolean values for optional features. Such features include allowing users to share their home directories under Samba or allowing Apache to serve files from users home directories which would otherwise be denied by the SELinux policy.  官网URL:http://wiki.centos.org/TipsAndTricks/SelinuxBooleans

5.        增加预设policy semanage

6.        创建自己的policy模块 audit2allow

适用于上述的方式(修改、恢复默认、无相应的布尔值等)都无法解决问题,或者为一些情况创建自己的policy模块来扩展selinux的policy。

举例:consider the postgrey service add-on for an smtp mail server. Our smtp server needs to communicate with postgrey over a Unix socket and that is something the default SELinux policy for our smtp server does not allow. Consequently the service is blocked by SELinux.

l         Selinux的状态改为permissive,运行一段时间,记录报警日志

l         生成自己的policy

# grep smtpd_t /var/log/audit/audit.log | audit2allow -m postgreylocal > postgreylocal.te

# cat postgreylocal.te

module postgreylocal 1.0;

require {

type postfix_smtpd_t;

type postfix_spool_t;

type initrc_t;

class sock_file write;

class unix_stream_socket connectto;

}

#============= postfix_smtpd_t ==============

allow postfix_smtpd_t initrc_t:unix_stream_socket connectto;

allow postfix_smtpd_t postfix_spool_t:sock_file write;

# grep smtpd_t /var/log/audit/audit.log | audit2allow -M postgreylocal  (当前目录下生成policy module,格式policy名称.pp和.te)

# semodule -i postgreylocal (将生成的policy加载,放在/etc/selinux/targeted/modules/active/modules目录下,格式policy名称.pp)

# semodule -l (确认是否正确加载)

l         We can then continue to monitor our SELinux log files to check that our custom policy module works and once we are satisfied we can re-enable SELinux Enforcing mode and again benefit from SELinux protection

7.        创建自己的policy模块并手工定制

Often audit2allow will automatically create a custom policy module that will resolve a particular issue, but there are times when it doesn’t get it quite right and we may want to manually edit and compile the policy module. For example, consider the following AVC audit log:

Summary:

SELinux is preventing postdrop (postfix_postdrop_t) “getattr” to /var/log/httpd/error_log (httpd_log_t).

Detailed Description:

SELinux denied access requested by postdrop. It is not expected that this access is required by postdrop and this access may signal an intrusion attempt. It is also possible that the specific version or configuration of the application is causing it to require additional access.

Allowing Access:

Sometimes labeling problems can cause SELinux denials. You could try to restore the default system file context for /var/log/httpd/error_log,

restorecon -v ‘/var/log/httpd/error_log’

If this does not work, there is currently no automatic way to allow this access.Instead, you can generate a local policy module to allow this access – see FAQ (http://fedora.redhat.com/docs/selinux-faq-fc5/#id2961385) Or you can disable SELinux protection altogether. Disabling SELinux protection is not recommended.

Additional Information:

Source Context                system_u:system_r:postfix_postdrop_t

Target Context                root:object_r:httpd_log_t

Target Objects                /var/log/httpd/error_log [ file ]

Source                        postdrop

Source Path                   /usr/sbin/postdrop

Port

Host                          sanitized

Local ID                      c303a4ea-8e7a-4acc-9118-9cc61c6a2ec8

Raw Audit Messages

host=sanitized type=AVC msg=audit(1218397672.372:352): avc:  denied  { getattr } for  pid=4262 comm=”postdrop” path=”/var/log/httpd/error_log” dev=md2 ino=117005 scontext=system_u:system_r:postfix_postdrop_t:s0 tcontext=root:object_r:httpd_log_t:s0 tclass=file

host=sanitized type=SYSCALL msg=audit(1218397672.372:352): arch=c000003e syscall=5 success=no exit=-13 a0=2 a1=7fffd6febca0 a2=7fffd6febca0 a3=0 items=0 ppid=4261 pid=4262 auid=4294967295 uid=48 gid=48 euid=48 suid=48 fsuid=48 egid=90 sgid=90 fsgid=90 tty=(none) comm=”postdrop” exe=”/usr/sbin/postdrop” subj=system_u:system_r:postfix_postdrop_t:s0 key=(null)

Running audit2allow on the above error, and reviewing the resultant postfixlocal.te policy file we see:

# grep postdrop /var/log/audit/audit.log | audit2allow -M postfixlocal(生成postfixlocal.te和pp)

# cat postfixlocal.te

module postfixlocal 1.0;

require {

type httpd_log_t;

type postfix_postdrop_t;

class dir getattr;

class file { read getattr };

}

#============= postfix_postdrop_t ==============

allow postfix_postdrop_t httpd_log_t:file getattr;

通过上述文件,产生的疑问是why does postdrop needs access to /var/log/httpd/error_log? 根据实际情况,有多个选择:1、We could just ignore the error and allow SELinux to continue blocking and logging access attempts or 2、we could allow the action by creating the custom policy module as suggested by audit2allow. 3、Alternatively we can edit the custom policy module .te file to prevent auditing of this particular error whilst still allowing SELinux to continue preventing access. We do this by editing the allow line, changing it to dontaudit:

#============= postfix_postdrop_t ==============

dontaudit postfix_postdrop_t httpd_log_t:file getattr; (修改,使之继续阻挡,但不记录日志)

Now we can manually compile and load the edited custom policy module:

# checkmodule -M -m -o postfixlocal.mod postfixlocal.te(checkmodule –Build base and policy modules。根据postfixlocal.te生成policy module– postfixlocal.mod)

# semodule_package -o postfixlocal.pp -m postfixlocal.mod(semodule_package – Create a SELinux policy module package)

# semodule -i postfixlocal.pp;semodule -l

Access to /var/log/httpd/error_log by postdrop will still be prevented by SELinux but we won’t receive constant alerts and error messages filling up our log files each time access is blocked.

8.        relabel 整个文件系统

Sometimes it is necessary to relabel the complete filesystem although this should only be necessary when enabling SELinux after it has been disabled or when changing the SELinux policy from the default targeted policy to strict. To automatically relabel the complete filesystem upon reboot, do:

# touch /.autorelabel

# reboot

Sometimes a complete filesystem relabel will fail if the system has been upgraded to CentOS-5.2 with SELinux disabled, and SELinux is then enabled. If the above procedure doesn’t correctly perform a complete filesystem relabel, try issuing the ‘genhomedircon’ command first:

# genhomedircon

# touch /.autorelabel

# reboot

二、配置文件、目录介绍

1.        配置文件

/etc/selinux目录的文件:

config:selinux的配置文件

restorecond.conf:

semanage.conf:semanage的配置文件

targeted:使用targeted方式的policy的目录

2.        目录

/etc/selinux/targeted下的三个目录

contexts(安全文本路径)—files/file_contexts(默认安全文本,建议通过semanage命令修改)

modules(模块)

policy—policy.21 (默认policy文件)

三、原理介绍

Selinux的三种access control:

Type Enforcement (TE): Type Enforcement is the primary mechanism of access control used in the targeted policy

Role-Based Access Control (RBAC): Based around SELinux users (not necessarily the same as the Linux user), but not used in the default targeted policy

Multi-Level Security (MLS): Not used and often hidden in the default targeted policy.

举例:查看安全性文本(security context)内容

$ ls -Z /var/www/html/index.html

-rw-r–r–  phil phil system_u:object_r:httpd_sys_content_t (user:role:type:mls) /var/www/html/index.html

# ps auxZ |grep httpd

root:system_r:httpd_t:s0(user:role:type:mls)        root     12926   0.0  1.8  22552  9360 ?        Ss   Apr06   0:00 /usr/sbin/httpd

注意:Within the default targeted policy, type is the important field used to implement Type Enforcement

Access is only allowed between similar types, so Apache running as httpd_t can read /var/www/html/index.html of type httpd_sys_content_t. Because Apache runs in the httpd_t domain, it can not access /home/phil/myfile.txt even though this file is world readable because it’s SELinux security context is not of type httpd_t. If Apache were to be exploited, it would not be able to start any process not in the httpd_t domain (which prevents escalation of privileges) or access any file not in an httpd_t related domain.

四、命令参考

————————————命令参考————————————-

所有查看安全性文本的命令,都是用参数 –Z,比如:ls –al –Z 参数,ps aux –Z 参数

getenforce—reports whether SELinux is enforcing, permissive, or disabled.

————————————

setenforce—modify the mode SELinux is running in.

setenforce [ Enforcing | Permissive | 1 | 0 ]

DESCRIPTION

Use  Enforcing or 1 to put SELinux in enforcing mode.  Use Permissive or 0 to put SELinux in permissive mode.  You need to modify /etc/grub.conf

or /etc/selinux/config to disable SELinux.

————————————

sestatus—SELinux status tool

sestatus [-v] [-b]

OPTIONS

-v        Checks  the contexts of a files , and a processes listed in the /etc/sestatus.conf file.  It also checks the context of the target, in cases of

symlinks.

-b       Display the current state of booleans.

FILES

/etc/sestatus.conf

————————————

restorecon [-Rv] 檔案或目錄

選項與參數:

-R  :根据目录的默认安全性文本,修改目录下所有文件的安全性文本;

-v  :將過程顯示到螢幕上;

-n  :不实际修改安全性文件,只是查看哪些文件需要修改;

————————————

chcon

# chcon [-R] [-t type] [-u user] [-r role] 檔案

# chcon [-R] –reference=範例檔 檔案

選項與參數:

-R  :連同該目錄下的次目錄也同時修改;

-t  :後面接安全性本文的類型欄位!例如 httpd_sys_content_t ;

-u  :後面接身份識別,例如 system_u;

-r  :後面街角色,例如 system_r;

–reference=範例檔:拿某個檔案當範例來修改後續接的檔案的類型!

————————————

selinuxenabled—tool to be used within shell scripts to determine if selinux is enabled用在shell脚本中的工具,判断selinux是否开启的判断命令

It exits with status 0 if SELinux is enabled and 1 if it is not enabled.

————————————

semanage -h

semanage {login|user|port|interface|node|fcontext} -l [-n]

semanage login -{a|d|m} [-sr] login_name

semanage user -{a|d|m} [-LrRP] selinux_name

semanage port -{a|d|m} [-tr] [ -p protocol ] port | port_range

semanage interface -{a|d|m} [-tr] interface_spec

semanage node -{a|d|m} [-tr] [ -p protocol ] [-M netmask] addr

semanage fcontext -{a|d|m} [-frst] file_spec

Primary Options:

-a, –add        Add a OBJECT record NAME

-d, –delete     Delete a OBJECT record NAME

-m, –modify     Modify a OBJECT record NAME

-l, –list       List the OBJECTS

-h, –help       Display this message

-n, –noheading  Do not print heading when listing OBJECTS

-S, –store      Select and alternate SELinux store to manage

Object-specific Options (see above):

-f, –ftype      File Type of OBJECT

“” (all files)

— (regular file)

-d (directory)

-c (character device)

-b (block device)

-s (socket)

-l (symbolic link)

-p (named pipe)

-p, –proto      Port protocol (tcp or udp) or internet protocol version of node (ipv4 or ipv6)

-M, –mask       Netmask

-P, –prefix     Prefix for home directory labeling

-L, –level      Default SELinux Level (MLS/MCS Systems only)

-R, –roles      SELinux Roles (ex: “sysadm_r staff_r”)

-s, –seuser     SELinux User Name

-t, –type       SELinux Type for the object

-r, –range      MLS/MCS Security Range (MLS/MCS Systems only)

————————————