赞
踩
http://www.centos.org/docs/5/html/Deployment_Guide-en-US/selg-overview.html
几乎可以肯定每个人都听说过 SELinux (更准确的说,尝试关闭过),甚至某些过往的经验让您对 SELinux 产生了偏见。不过随着日益增长的 0-day 安全漏洞,或许现在是时候去了解下这个在 Linux 内核中已经有8年历史的强制性访问控制系统(MAC)了。
SELinux 与强制访问控制系统
SELinux 全称 Security Enhanced Linux (安全强化 Linux),是 MAC (Mandatory Access Control,强制访问控制系统)的一个实现,目的在于明确的指明某个进程可以访问哪些资源(文件、网络端口等)。
强制访问控制系统的用途在于增强系统抵御 0-Day 攻击(利用尚未公开的漏洞实现的攻击行为)的能力。所以它不是网络防火墙或 ACL 的替代品,在用途上也不重复。
举例来说,系统上的 Apache 被发现存在一个漏洞,使得某远程用户可以访问系统上的敏感文件(比如 /etc/passwd
来获得系统已存在用户),而修复该安全漏洞的 Apache 更新补丁尚未释出。此时SELinux 可以起到弥补该漏洞的缓和方案。因为 /etc/passwd 不具有 Apache 的访问标签,所以 Apache 对于/etc/passwd
的访问会被 SELinux 阻止。
相比其他强制性访问控制系统,SELinux 有如下优势:
那么 SELinux 对于系统性能有什么样的影响呢?根据 Phoronix 在 2009 年使用 Fedora 11 所做的横向比较来看,开启 SELinux 仅在少数情况下导致系统性能约 5% 的降低。
SELinux 是不是会十分影响一般桌面应用及程序开发呢?原先是,因为 SELinux 的策略主要针对服务器环境。但随着 SELinux 8年来的广泛应用,目前SELinux 策略在一般桌面及程序开发环境下依然可以同时满足安全性及便利性的要求。以刚刚发布的 Fedora 15 为例,笔者在搭建完整的娱乐(包含多款第三方原生 Linux 游戏及 Wine 游戏)及开发环境(Android SDK + Eclipse)过程中,只有 Wine 程序的首次运行时受到 SELinux 默认策略的阻拦,在图形化的“SELinux 故障排除程序”帮助下,点击一下按钮就解决了。
了解和配置 SELinux
1. 获取当前 SELinux 运行状态
getenforce
可能返回结果有三种:Enforcing
、Permissive
和 Disabled
。Disabled 代表 SELinux 被禁用,Permissive 代表仅记录安全警告但不阻止可疑行为,Enforcing 代表记录警告且阻止可疑行为。
目前常见发行版中,RHEL 和 Fedora 默认设置为 Enforcing,其余的如 openSUSE 等为 Permissive。
2. 改变 SELinux 运行状态
setenforce [ Enforcing | Permissive | 1 | 0 ]
该命令可以立刻改变 SELinux 运行状态,在 Enforcing 和 Permissive 之间切换,结果保持至关机。一个典型的用途是看看到底是不是 SELinux 导致某个服务或者程序无法运行。若是在 setenforce 0 之后服务或者程序依然无法运行,那么就可以肯定不是 SELinux 导致的。
若是想要永久变更系统 SELinux 运行环境,可以通过更改配置文件 /etc/sysconfig/selinux
实现。注意当从 Disabled 切换到 Permissive 或者 Enforcing 模式后需要重启计算机并为整个文件系统重新创建安全标签(touch /.autorelabel && reboot
)。
3. SELinux 运行策略
配置文件 /etc/sysconfig/selinux
还包含了 SELinux 运行策略的信息,通过改变变量 SELINUXTYPE
的值实现,该值有两种可能:targeted
代表仅针对预制的几种网络服务和访问请求使用 SELinux 保护,strict
代表所有网络服务和访问请求都要经过 SELinux。
RHEL 和 Fedora 默认设置为 targeted
,包含了对几乎所有常见网络服务的 SELinux 策略配置,已经默认安装并且可以无需修改直接使用。
若是想自己编辑 SELinux 策略,也提供了命令行下的策略编辑器 seedit
以及 Eclipse 下的编辑插件 eclipse-slide
。
4. coreutils 工具的 SELinux 模式
常见的属于 coreutils 的工具如 ps
、ls
等等,可以通过增加 Z
选项的方式获知 SELinux 方面的信息。
如 ps auxZ | grep lldpad
system_u:system_r:initrc_t:s0 root 1000 8.9 0.0 3040 668 ? Ss 21:01 6:08 /usr/sbin/lldpad -d
如 ls -Z /usr/lib/xulrunner-2/libmozjs.so
-rwxr-xr-x. root root system_u:object_r:lib_t:s0 /usr/lib/xulrunner-2/libmozjs.so
以此类推,Z
选项可以应用在几乎全部 coreutils
工具里。
Apache SELinux 配置实例
1. 让 Apache 可以访问位于非默认目录下的网站文件
首先,用 semanage fcontext -l | grep '/var/www'
获知默认 /var/www
目录的 SELinux 上下文:
/var/www(/.*)? all files system_u:object_r:httpd_sys_content_t:s0
从中可以看到 Apache 只能访问包含 httpd_sys_content_t
标签的文件。
假设希望 Apache 使用 /srv/www
作为网站文件目录,那么就需要给这个目录下的文件增加 httpd_sys_content_t
标签,分两步实现。
首先为 /srv/www 这个目录下的文件添加默认标签类型:semanage fcontext -a -t httpd_sys_content_t '/srv/www(/.*)?'
然后用新的标签类型标注已有文件:restorecon -Rv /srv/www
之后 Apache 就可以使用该目录下的文件构建网站了。
其中 restorecon
在 SELinux 管理中很常见,起到恢复文件默认标签的作用。比如当从用户主目录下将某个文件复制到 Apache 网站目录下时,Apache 默认是无法访问,因为用户主目录的下的文件标签是user_home_t
。此时就需要 restorecon
将其恢复为可被 Apache 访问的 httpd_sys_content_t
类型:
restorecon reset /srv/www/foo.com/html/file.html context unconfined_u:object_r:user_home_t:s0->system_u:object_r:httpd_sys_content_t:s0
2. 让 Apache 侦听非标准端口
默认情况下 Apache 只侦听 80 和 443 两个端口,若是直接指定其侦听 888 端口的话,会在 service httpd restart
的时候报错:
Starting httpd: (13)Permission denied: make_sock: could not bind to address [::]:888
(13)Permission denied: make_sock: could not bind to address 0.0.0.0:888
no listening sockets available, shutting down
Unable to open logs
这个时候,若是在桌面环境下 SELinux 故障排除工具应该已经弹出来报错了。若是在终端下,可以通过查看 /var/log/messages 日志然后用 sealert -l 加编号的方式查看,或者直接使用 sealert -b
浏览。无论哪种方式,内容和以下会比较类似:
SELinux is preventing /usr/sbin/httpd from name_bind access on the tcp_socket port 888.
***** Plugin bind_ports (92.2 confidence) suggests *************************
If you want to allow /usr/sbin/httpd to bind to network port 888
Then you need to modify the port type.
Do
# semanage port -a -t PORT_TYPE -p tcp 888
`where PORT_TYPE is one of the following: ntop_port_t, http_cache_port_t, http_port_t.`
***** Plugin catchall_boolean (7.83 confidence) suggests *******************
If you want to allow system to run with NIS
Then you must tell SELinux about this by enabling the 'allow_ypbind' boolean.
Do
setsebool -P allow_ypbind 1
***** Plugin catchall (1.41 confidence) suggests ***************************
If you believe that httpd should be allowed name_bind access on the port 888 tcp_socket by default.
Then you should report this as a bug.
You can generate a local policy module to allow this access.
Do
allow this access for now by executing:
# grep httpd /var/log/audit/audit.log | audit2allow -M mypol
# semodule -i mypol.pp
可以看出 SELinux 根据三种不同情况分别给出了对应的解决方法。在这里,第一种情况是我们想要的,于是按照其建议输入:
semanage port -a -t http_port_t -p tcp 888
之后再次启动 Apache 服务就不会有问题了。
这里又可以见到 semanage
这个 SELinux 管理配置工具。它第一个选项代表要更改的类型,然后紧跟所要进行操作。详细内容参考Man 手册
3. 允许 Apache 访问创建私人网站
若是希望用户可以通过在 ~/public_html/
放置文件的方式创建自己的个人网站的话,那么需要在 Apache 策略中允许该操作执行。使用:
setsebool httpd_enable_homedirs 1
setsebool
是用来切换由布尔值控制的 SELinux 策略的,当前布尔值策略的状态可以通过 getsebool
来获知。
默认情况下 setsebool 的设置只保留到下一次重启之前,若是想永久生效的话,需要添加 -P
参数,比如:
setsebool -P httpd_enable_homedirs 1
总结
希望通过这一个简短的教程,扫除您对 SELinux 的误解甚至恐惧,个人感觉它并不比 iptables 策略复杂。如果希望您的服务器能有效抵挡 0-day 攻击时,那么 SELinux 或许就是一个值得考虑的缓和方案。
This section provides a basic introduction to Access Control Mechanisms (ACMs).ACMs provide a means for system administrators to control which users and processes can access different files, devices, interfaces, etc., in a computer system. This is a primary consideration when securing a computer system or network of any size.
Discretionary Access Control (DAC) defines the basic access controls for objects in a filesystem. This is the typical access control provided by file permissions, sharing, etc. Such access is generally at the discretion of the owner of the object (file, directory, device, etc.).
DAC provides a means of restricting access to objects based on the identity of the users or groups (subjects) that try to access those objects. Depending on a subject's access permissions, they may also be able to pass permissions to other subjects.
Access Control Lists (ACLs) provide further control over which objects a subject can access. For more information, refer toChapter 8, Access Control Lists.
Mandatory Access Control (MAC) is a security mechanism that restricts the level of control that users (subjects) have over the objects that they create. Unlike in aDAC implementation, where users have full control over their own files, directories, etc.,MAC adds additional labels, or categories, to all file system objects. Users and processes must have the appropriate access to these categories before they can interact with these objects.
In Red Hat Enterprise Linux, MAC is enforced by SELinux. For more information, refer toSection 43.2, “Introduction to SELinux”.
Role-based Access Control (RBAC) is an alternative method of controlling user access to file system objects. Instead of access being controlled by user permissions, the system administrator establishesRoles based on business functional requirements or similar criteria. These Roles have different types and levels of access to objects.
In contrast to DAC or MAC systems, where users have access to objects based on their own and the object's permissions, users in anRBAC system must be members of the appropriate group, or Role, before they can interact with files, directories, devices, etc.
From an administrative point of view, this makes it easier to control who has access to various parts of the file system, just by controlling their group memberships.
Multi-Level Security (MLS) is a specific Mandatory Access Control (MAC) security scheme. Under this scheme, processes are called Subjects. Files, sockets and other passive operating system entities are called Objects. For more information, refer to Section 43.6, “Multi-Level Security (MLS)”.
Multi-Category Security (MCS) is an enhancement to SELinux, and allows users to label files with categories.MCS is an adaptation ofMLSand re-uses much of theMLS framework in SELinux. For more information, refer toSection 43.4.1, “Introduction”
-----------------------------------------------------------------
Security-Enhanced Linux (SELinux) is a security architecture integrated into the 2.6.x kernel using theLinux Security Modules (LSM). It is a project of the United States National Security Agency (NSA) and the SELinux community. SELinux integration into Red Hat Enterprise Linux was a joint effort between the NSA and Red Hat.
SELinux provides a flexible Mandatory Access Control (MAC) system built into the Linux kernel. Under standard LinuxDiscretionary Access Control (DAC), an application or process running as a user (UID or SUID) has the user's permissions to objects such as files, sockets, and other processes. Running aMAC kernel protects the system from malicious or flawed applications that can damage or destroy the system.
SELinux defines the access and transition rights of every user, application, process, and file on the system. SELinux then governs the interactions of these entities using a security policy that specifies how strict or lenient a given Red Hat Enterprise Linux installation should be.
On a day-to-day basis, system users will be largely unaware of SELinux. Only system administrators need to consider how strict a policy to implement for their server environment. The policy can be as strict or as lenient as needed, and is very finely detailed. This detail gives the SELinux kernel complete, granular control over the entire system.
When a subject, (for example, an application), attempts to access an object (for example, a file), the policy enforcement server in the kernel checks anaccess vector cache (AVC), where subject and object permissions are cached. If a decision cannot be made based on data in theAVC, the request continues to the security server, which looks up thesecurity context of the application and the file in a matrix. Permission is then granted or denied, with anavc: denied message detailed in/var/log/messages if permission is denied. The security context of subjects and objects is applied from the installed policy, which also provides the information to populate the security server's matrix.
Refer to the following diagram:
Instead of running in enforcing mode, SELinux can run inpermissive mode, where theAVC is checked and denials are logged, but SELinux does not enforce the policy. This can be useful for troubleshooting and for developing or fine-tuning SELinux policy.
For more information about how SELinux works, refer to Section 43.2.3, “Additional Resources”.
The following sections describe SELinux configuration files and related file systems.
The /selinux/ pseudo-file system contains commands that are most commonly used by the kernel subsystem. This type of file system is similar to the/proc/ pseudo-file system.
Administrators and users do not normally need to manipulate this component.
The following example shows sample contents of the /selinux/ directory:
-rw-rw-rw- 1 root root 0 Sep 22 13:14 access dr-xr-xr-x 1 root root 0 Sep 22 13:14 booleans --w------- 1 root root 0 Sep 22 13:14 commit_pending_bools -rw-rw-rw- 1 root root 0 Sep 22 13:14 context -rw-rw-rw- 1 root root 0 Sep 22 13:14 create --w------- 1 root root 0 Sep 22 13:14 disable -rw-r--r-- 1 root root 0 Sep 22 13:14 enforce -rw------- 1 root root 0 Sep 22 13:14 load -r--r--r-- 1 root root 0 Sep 22 13:14 mls -r--r--r-- 1 root root 0 Sep 22 13:14 policyvers -rw-rw-rw- 1 root root 0 Sep 22 13:14 relabel -rw-rw-rw- 1 root root 0 Sep 22 13:14 user
For example, running the cat command on the enforce file reveals either a 1 for enforcing mode or0 for permissive mode.
The following sections describe SELinux configuration and policy files, and related file systems located in the/etc/ directory.
There are two ways to configure SELinux under Red Hat Enterprise Linux: using theSecurity Level Configuration Tool (system-config-selinux), or manually editing the configuration file (/etc/sysconfig/selinux).
The /etc/sysconfig/selinux file is the primary configuration file for enabling or disabling SELinux, as well as for setting which policy to enforce on the system and how to enforce it.
The /etc/sysconfig/selinux contains a symbolic link to the actual configuration file,/etc/selinux/config.
The following explains the full subset of options available for configuration:
SELINUX=enforcing|permissive|disabled — Defines the top-level state of SELinux on a system.
enforcing — The SELinux security policy is enforced.
permissive — The SELinux system prints warnings but does not enforce policy.
This is useful for debugging and troubleshooting purposes. In permissive mode, more denials are logged because subjects can continue with actions that would otherwise be denied in enforcing mode. For example, traversing a directory tree in permissive mode produces avc: denied messages for every directory level read. In enforcing mode, SELinux would have stopped the initial traversal and kept further denial messages from occurring.
disabled — SELinux is fully disabled. SELinux hooks are disengaged from the kernel and the pseudo-file system is unregistered.
Actions made while SELinux is disabled may result in the file system no longer having the correct security context. That is, the security context defined by the policy. The best way to relabel the file system is to create the flag file/.autorelabel and reboot the machine. This causes the relabel to occur very early in the boot process, before any processes are running on the system. Using this procedure means that processes can not accidentally create files in the wrong context or start up in the wrong context.
It is possible to use the fixfiles relabel command prior to enabling SELinux to relabel the file system. This method is not recommended, however, because after it is complete, it is still possible to have processes potentially running on the system in the wrong context. These processes could create files that would also be in the wrong context.
SELINUXTYPE=targeted|strict — Specifies which policy SELinux should enforce.
targeted — Only targeted network daemons are protected.
The following daemons are protected in the default targeted policy: dhcpd, httpd (apache.te), named, nscd, ntpd, portmap, snmpd, squid, and syslogd. The rest of the system runs in the unconfined_t domain. This domain allows subjects and objects with that security context to operate using standard Linux security.
The policy files for these daemons are located in /etc/selinux/targeted/src/policy/domains/program. These files are subject to change as newer versions of Red Hat Enterprise Linux are released.
Policy enforcement for these daemons can be turned on or off, using Boolean values controlled by theSecurity Level Configuration Tool (system-config-selinux).
Setting a Boolean value for a targeted daemon to 0 (zero) disables policy transition for the daemon. For example, you can setdhcpd_disable_trans to0 to preventinit from transitioningdhcpd from theunconfined_t domain to the domain specified indhcpd.te.
Use the getsebool -a command to list all SELinux booleans. The following is an example of using thesetsebool command to set an SELinux boolean. The-P option makes the change permanent. Without this option, the boolean would be reset to1 at reboot.
setsebool -P dhcpd_disable_trans=0
strict — Full SELinux protection, for all daemons. Security contexts are defined for all subjects and objects, and every action is processed by the policy enforcement server.
SETLOCALDEFS=0|1 — Controls how local definitions (users and booleans) are set. Set this value to 1 to have these definitions controlled byload_policy from files in/etc/selinux/<policyname>. or set it to 0 to have them controlled bysemanage.
The /etc/selinux/ directory is the primary location for all policy files as well as the main configuration file.
The following example shows sample contents of the /etc/selinux/ directory:
-rw-r--r-- 1 root root 448 Sep 22 17:34 config drwxr-xr-x 5 root root 4096 Sep 22 17:27 strict drwxr-xr-x 5 root root 4096 Sep 22 17:28 targeted
The two subdirectories, strict/ and targeted/, are the specific directories where the policy files of the same name (that is,strict andtargeted) are contained.
The following are some of the commonly used SELinux utilities:
/usr/sbin/setenforce — Modifies in real-time the mode in which SELinux runs.
For example:
setenforce 1 — SELinux runs in enforcing mode.
setenforce 0 — SELinux runs in permissive mode.
To actually disable SELinux, you need to either specify the appropriate setenforce parameter in /etc/sysconfig/selinux or pass the parameterselinux=0 to the kernel, either in/etc/grub.conf or at boot time.
/usr/sbin/sestatus -v — Displays the detailed status of a system running SELinux. The following example shows an excerpt ofsestatus -v output:
SELinux status: enabled SELinuxfs mount: /selinux Current mode: enforcing Mode from config file: enforcing Policy version: 21 Policy from config file: targeted Process contexts: Current context: user_u:system_r:unconfined_t:s0 Init context: system_u:system_r:init_t:s0 /sbin/mingetty system_u:system_r:getty_t:s0
/usr/bin/newrole — Runs a new shell in a new context, or role. Policy must allow the transition to the new role.
/sbin/restorecon — Sets the security context of one or more files by marking the extended attributes with the appropriate file or security context.
/sbin/fixfiles — Checks or corrects the security context database on the file system.
Refer to the man page associated with these utilities for more information.
Refer to the setools or policycoreutils package contents for more information on all available binary utilities. To view the contents of a package, use the following command:
rpm -ql <package-name>
Refer to the following resources for more detailed information on SELinux.
/usr/share/doc/setools-<version-number>/ All documentation for utilities contained in thesetools package. This includes all helper scripts, sample configuration files, and documentation.
http://www.nsa.gov/selinux/ Homepage for the NSA SELinux development team. Many resources are available in HTML and PDF formats. Although many of these links are not SELinux specific, some concepts may apply.
http://fedora.redhat.com/docs/ Homepage for the Fedora documentation project, which contains Fedora Core specific materials that may be more timely, since the release cycle is much shorter.
http://selinux.sourceforge.net Homepage for the SELinux community.
-----------------------------------------------------------------
Security-Enhanced Linux (SELinux) is a security architecture integrated into the 2.6.x kernel using theLinux Security Modules (LSM). It is a project of the United States National Security Agency (NSA) and the SELinux community. SELinux integration into Red Hat Enterprise Linux was a joint effort between the NSA and Red Hat.
SELinux provides a flexible Mandatory Access Control (MAC) system built into the Linux kernel. Under standard LinuxDiscretionary Access Control (DAC), an application or process running as a user (UID or SUID) has the user's permissions to objects such as files, sockets, and other processes. Running aMAC kernel protects the system from malicious or flawed applications that can damage or destroy the system.
SELinux defines the access and transition rights of every user, application, process, and file on the system. SELinux then governs the interactions of these entities using a security policy that specifies how strict or lenient a given Red Hat Enterprise Linux installation should be.
On a day-to-day basis, system users will be largely unaware of SELinux. Only system administrators need to consider how strict a policy to implement for their server environment. The policy can be as strict or as lenient as needed, and is very finely detailed. This detail gives the SELinux kernel complete, granular control over the entire system.
When a subject, (for example, an application), attempts to access an object (for example, a file), the policy enforcement server in the kernel checks anaccess vector cache (AVC), where subject and object permissions are cached. If a decision cannot be made based on data in theAVC, the request continues to the security server, which looks up thesecurity context of the application and the file in a matrix. Permission is then granted or denied, with anavc: denied message detailed in/var/log/messages if permission is denied. The security context of subjects and objects is applied from the installed policy, which also provides the information to populate the security server's matrix.
Refer to the following diagram:
Instead of running in enforcing mode, SELinux can run inpermissive mode, where theAVC is checked and denials are logged, but SELinux does not enforce the policy. This can be useful for troubleshooting and for developing or fine-tuning SELinux policy.
For more information about how SELinux works, refer to Section 43.2.3, “Additional Resources”.
The following sections describe SELinux configuration files and related file systems.
The /selinux/ pseudo-file system contains commands that are most commonly used by the kernel subsystem. This type of file system is similar to the/proc/ pseudo-file system.
Administrators and users do not normally need to manipulate this component.
The following example shows sample contents of the /selinux/ directory:
-rw-rw-rw- 1 root root 0 Sep 22 13:14 access dr-xr-xr-x 1 root root 0 Sep 22 13:14 booleans --w------- 1 root root 0 Sep 22 13:14 commit_pending_bools -rw-rw-rw- 1 root root 0 Sep 22 13:14 context -rw-rw-rw- 1 root root 0 Sep 22 13:14 create --w------- 1 root root 0 Sep 22 13:14 disable -rw-r--r-- 1 root root 0 Sep 22 13:14 enforce -rw------- 1 root root 0 Sep 22 13:14 load -r--r--r-- 1 root root 0 Sep 22 13:14 mls -r--r--r-- 1 root root 0 Sep 22 13:14 policyvers -rw-rw-rw- 1 root root 0 Sep 22 13:14 relabel -rw-rw-rw- 1 root root 0 Sep 22 13:14 user
For example, running the cat command on the enforce file reveals either a 1 for enforcing mode or0 for permissive mode.
The following sections describe SELinux configuration and policy files, and related file systems located in the/etc/ directory.
There are two ways to configure SELinux under Red Hat Enterprise Linux: using theSecurity Level Configuration Tool (system-config-selinux), or manually editing the configuration file (/etc/sysconfig/selinux).
The /etc/sysconfig/selinux file is the primary configuration file for enabling or disabling SELinux, as well as for setting which policy to enforce on the system and how to enforce it.
The /etc/sysconfig/selinux contains a symbolic link to the actual configuration file,/etc/selinux/config.
The following explains the full subset of options available for configuration:
SELINUX=enforcing|permissive|disabled — Defines the top-level state of SELinux on a system.
enforcing — The SELinux security policy is enforced.
permissive — The SELinux system prints warnings but does not enforce policy.
This is useful for debugging and troubleshooting purposes. In permissive mode, more denials are logged because subjects can continue with actions that would otherwise be denied in enforcing mode. For example, traversing a directory tree in permissive mode produces avc: denied messages for every directory level read. In enforcing mode, SELinux would have stopped the initial traversal and kept further denial messages from occurring.
disabled — SELinux is fully disabled. SELinux hooks are disengaged from the kernel and the pseudo-file system is unregistered.
Actions made while SELinux is disabled may result in the file system no longer having the correct security context. That is, the security context defined by the policy. The best way to relabel the file system is to create the flag file/.autorelabel and reboot the machine. This causes the relabel to occur very early in the boot process, before any processes are running on the system. Using this procedure means that processes can not accidentally create files in the wrong context or start up in the wrong context.
It is possible to use the fixfiles relabel command prior to enabling SELinux to relabel the file system. This method is not recommended, however, because after it is complete, it is still possible to have processes potentially running on the system in the wrong context. These processes could create files that would also be in the wrong context.
SELINUXTYPE=targeted|strict — Specifies which policy SELinux should enforce.
targeted — Only targeted network daemons are protected.
The following daemons are protected in the default targeted policy: dhcpd, httpd (apache.te), named, nscd, ntpd, portmap, snmpd, squid, and syslogd. The rest of the system runs in the unconfined_t domain. This domain allows subjects and objects with that security context to operate using standard Linux security.
The policy files for these daemons are located in /etc/selinux/targeted/src/policy/domains/program. These files are subject to change as newer versions of Red Hat Enterprise Linux are released.
Policy enforcement for these daemons can be turned on or off, using Boolean values controlled by theSecurity Level Configuration Tool (system-config-selinux).
Setting a Boolean value for a targeted daemon to 0 (zero) disables policy transition for the daemon. For example, you can setdhcpd_disable_trans to0 to preventinit from transitioningdhcpd from theunconfined_t domain to the domain specified indhcpd.te.
Use the getsebool -a command to list all SELinux booleans. The following is an example of using thesetsebool command to set an SELinux boolean. The-P option makes the change permanent. Without this option, the boolean would be reset to1 at reboot.
setsebool -P dhcpd_disable_trans=0
strict — Full SELinux protection, for all daemons. Security contexts are defined for all subjects and objects, and every action is processed by the policy enforcement server.
SETLOCALDEFS=0|1 — Controls how local definitions (users and booleans) are set. Set this value to 1 to have these definitions controlled byload_policy from files in/etc/selinux/<policyname>. or set it to 0 to have them controlled bysemanage.
The /etc/selinux/ directory is the primary location for all policy files as well as the main configuration file.
The following example shows sample contents of the /etc/selinux/ directory:
-rw-r--r-- 1 root root 448 Sep 22 17:34 config drwxr-xr-x 5 root root 4096 Sep 22 17:27 strict drwxr-xr-x 5 root root 4096 Sep 22 17:28 targeted
The two subdirectories, strict/ and targeted/, are the specific directories where the policy files of the same name (that is,strict andtargeted) are contained.
The following are some of the commonly used SELinux utilities:
/usr/sbin/setenforce — Modifies in real-time the mode in which SELinux runs.
For example:
setenforce 1 — SELinux runs in enforcing mode.
setenforce 0 — SELinux runs in permissive mode.
To actually disable SELinux, you need to either specify the appropriate setenforce parameter in /etc/sysconfig/selinux or pass the parameterselinux=0 to the kernel, either in/etc/grub.conf or at boot time.
/usr/sbin/sestatus -v — Displays the detailed status of a system running SELinux. The following example shows an excerpt ofsestatus -v output:
SELinux status: enabled SELinuxfs mount: /selinux Current mode: enforcing Mode from config file: enforcing Policy version: 21 Policy from config file: targeted Process contexts: Current context: user_u:system_r:unconfined_t:s0 Init context: system_u:system_r:init_t:s0 /sbin/mingetty system_u:system_r:getty_t:s0
/usr/bin/newrole — Runs a new shell in a new context, or role. Policy must allow the transition to the new role.
/sbin/restorecon — Sets the security context of one or more files by marking the extended attributes with the appropriate file or security context.
/sbin/fixfiles — Checks or corrects the security context database on the file system.
Refer to the man page associated with these utilities for more information.
Refer to the setools or policycoreutils package contents for more information on all available binary utilities. To view the contents of a package, use the following command:
rpm -ql <package-name>
Refer to the following resources for more detailed information on SELinux.
/usr/share/doc/setools-<version-number>/ All documentation for utilities contained in thesetools package. This includes all helper scripts, sample configuration files, and documentation.
http://www.nsa.gov/selinux/ Homepage for the NSA SELinux development team. Many resources are available in HTML and PDF formats. Although many of these links are not SELinux specific, some concepts may apply.
http://fedora.redhat.com/docs/ Homepage for the Fedora documentation project, which contains Fedora Core specific materials that may be more timely, since the release cycle is much shorter.
http://selinux.sourceforge.net Homepage for the SELinux community.
-----------------------------------------------------------------
Multi-Category Security (MCS) is an enhancement to SELinux, and allows users to label files with categories. These categories are used to further constrainDiscretionary Access Control (DAC) andType Enforcement (TE) logic. They may also be used when displaying or printing files. An example of a category is "Company_Confidential". Only users with access to this category can access files labeled with the category, assuming the existing DAC and TE rules also permit access.
The term categories refers to the same non-hierarchical categories used byMulti-Level Security (MLS). UnderMLS, objects and subjects are labeled with Security Levels. These Security Levels consist of a hierarchical sensitivity value (such as "Top Secret") and zero or more non-hierarchical categories (such as "Crypto"). Categories provide compartments within sensitivity levels and enforce the need-to-know security principle. Refer to Section 43.6, “Multi-Level Security (MLS)” for more information about Multi-Level Security.
MCS is an adaptation of MLS. From a technical point of view,MCS is a policy change, combined with a few userland modifications to hide some of the unneededMLS technology. Some kernel changes were also made, but only relating to making it easy to upgrade toMCS (orMLS) without invoking a full file system relabel.
The hope is to improve the quality of the system as a whole, reduce costs, leverage the open source process, increase transparency, and make the technology base useful to more than a small group of extremely special-case users.
Beyond access control, MCS could be used to display theMCS categories at the top and bottom of printed pages. This may also include a cover sheet to indicate document handling procedures. It should also be possible to integrateMCS with future developments in SELinux, such as Security Enhanced X. Integration with a directory server will also makeMCS support for email easier. This could involve users manually labeling outgoing emails or by attaching suitably labeled files. The email client can then determine whether the recipients are known to be cleared to access the categories associated with the emails.
SELinux stores security contexts as an extended attribute of a file. The "security." namespace is used for security modules, and the security.selinux name is used to persistently store SELinux security labels on files. The contents of this attribute will vary depending on the file or directory you inspect and the policy the machine is enforcing.
This is expected to change in the 2.6.15 kernel (and already has in the latest -mm kernels), so thatgetxattr(2) always returns the kernel's canonicalized version of the label.
You can use the ls -Z command to view the category label of a file:
[root@myServer ~]# ls -Z gravityControl.txt -rw-r--r-- user user user_u:object_r:tmp_t:Moonbase_Plans gravityControl.txt
You can use the gefattr(1) command to view the internal category value (c10):
[root@myServer ~]# getfattr -n security.selinux gravityControl.txt # file: gravityControl.txt security.selinux="user_u:object_r:tmp_t:s0:c10\000"
Refer to Section 43.5, “Getting Started with Multi-Category Security (MCS)” for details on creating categories and assigning them to files.
--------------------------------------------------------------
Getting Started with Multi-Category Security (MCS)
This section provides an introduction to using MCS labels to extend the Mandatory Access Control (MAC) capabilities of SELinux. It discusses MCS categories, SELinux user identities, and how they apply to Linux user accounts and files. It builds on the conceptual information provided in Section 43.4, “Multi-Category Security (MCS)”, and introduces some basic examples of usage.
MCS labeling from a user and system administrator standpoint is straightforward. It consists of configuring a set of categories, which are simply text labels, such as "Company_Confidential" or "Medical_Records", and then assigning users to those categories. The system administrator first configures the categories, then assigns users to them as required. The users can then use the labels as they see fit.
The names of the categories and their meanings are set by the system administrator, and can be set to whatever is required for the specific deployment. A system in a home environment may have only one category of "Private", and be configured so that only trusted local users are assigned to this category.
In a corporate environment, categories could be used to identify documents confidential to specific departments. Categories could be established for "Finance", "Payroll", "Marketing", and "Personnel". Only users assigned to those categories can access resources labeled with the same category.
After users have been assigned to categories, they can label any of their own files with any of the categories to which they have been assigned. For example, a home user in the system described above could label all of their personal files as "Private", and no service such as Apache or vsftp would ever be able to access those files, because they don't have access to the "Private" category.
MCS works on a simple principle: to access a file, a user needs to be assigned to all of the categories with which the file is labeled. The MCS check is applied after normal Linux Discretionary Access Control (DAC) and Type Enforcement (TE) rules, so it can only further restrict security.
SELinux maintains its own user identity for processes, separately from Linux user identities. In the targeted policy (the default for Red Hat Enterprise Linux), only a minimal number of SELinux user identities exist:
system_u — System processes
root — System administrator
user_u — All login users
Use the semanage user -l command to list SELinux users:
[root@dhcp-133 ~]# semanage user -l Labeling MLS/ MLS/ SELinux User Prefix MCS Level MCS Range SELinux Roles root user s0 s0-s0:c0.c1023 system_r sysadm_r user_r system_u user s0 s0-s0:c0.c1023 system_r user_u user s0 s0-s0:c0.c1023 system_r sysadm_r user_r
Refer to Section 43.8.3, “Understanding the Users and Roles in the Targeted Policy” for more information about SELinux users and roles.
One of the properties of targeted policy is that login users all run in the same security context. From a TE point of view, in targeted policy, they are security-equivalent. To effectivly use MCS, however, we need to be able to assign different sets of categories to different Linux users, even though they are all the same SELinux user (user_u). This is solved by introducing the concept of an SELinux login. This is used during the login process to assign MCS categories to Linux users when their shell is launched.
Use the semanage login -a command to assign Linux users to SELinux user identities:
# semanage login -a james # semanage login -a daniel # semanage login -a olga
Now when you list the SELinux users, you can see the Linux users assigned to a specific SELinux user identity:
# semanage login -l Login Name SELinux User MLS/MCS Range __default__ user_u s0 james user_u s0 daniel user_u s0 root root SystemLow-SystemHigh olga user_u s0
Notice that at this stage only the root account is assigned to any categories. By default, the root account is configured with access to all categories.
Red Hat Enterprise Linux and SELinux are preconfigured with several default categories, but to make effective use of MCS, the system administrator typically modifies these or creates further categories to suit local requirements.
SELinux maintains a mapping between internal sensitivity and category levels and their human-readable representations in thesetrans.conf file. The system administrator edits this file to manage and maintain the required categories.
Use the chcat -L command to list the current categories:
[root@dhcp-133 tmp]# chcat -L s0:c0 CompanyConfidential s0:c3 TopSecret s0 s0-s0:c0.c255 SystemLow-SystemHigh s0:c0.c255 SystemHigh
To modify the categories or to start creating your own, modify the /etc/selinux/<selinuxtype>/setrans.conf file. For the example introduced above, add the Marketing, Finance, Payroll, and Personnel categories as follows (this example uses the targeted policy, and irrelevant sections of the file have been omitted):
[root@dhcp-133 tmp]# vi /etc/selinux/targeted/setrans.conf s0:c0=Marketing s0:c1=Finance s0:c2=Payroll s0:c3=Personnel
Use the chcat -L command to check the newly-added categories:
[root@dhcp-133 tmp]# chcat -L s0:c0 Marketing s0:c1 Finance s0:c2 Payroll s0:c3 Personnel s0 s0-s0:c0.c255 SystemLow-SystemHigh s0:c0.c255 SystemHigh
Now that the required categories have been added to the system, you can start assigning them to SELinux users and files. To further develop the example above, assume that James is in the Marketing department, Daniel is in the Finance and Payroll departments, and Olga is in the Personnel department. Each of these users has already been assigned an SELinux login.
Use the chcat command to assign MCS categories to SELinux logins:
[root@dhcp-133 ~]# chcat -l -- +Marketing james [root@dhcp-133 ~]# chcat -l -- +Finance,+Payroll daniel [root@dhcp-133 ~]# chcat -l -- +Personnel olga
You can also use the chcat command with additional command-line arguments to list the categories that are assigned to users:
[root@dhcp-133 ~]# chcat -L -l daniel james olga daniel: Finance,Payroll james: Marketing olga: Personnel
You can add further Linux users, assign them to SELinux user identities and then assign categories to them as required. For example, if the company director also requires a user account with access to all categories, follow the same procedure as above:
# Create a user account for the company director (Karl) [root@dhcp-133 ~]# useradd karl [root@dhcp-133 ~]# passwd karl Changing password for user karl. New UNIX password: Retype new UNIX password: passwd: all authentication tokens updated successfully. # Assign the user account to an SELinux login [root@dhcp-133 ~]# semanage login -a karl # Assign all the MCS categories to the new login [root@dhcp-133 ~]# chcat -l -- +Marketing,+Finance,+Payroll,+Personnel karl
Use the chcat command to verify the addition of the new user:
[root@dhcp-133 ~]# chcat -L -l daniel james olga karl daniel: Finance,Payroll james: Marketing olga: Personnel karl: Marketing,Finance,Payroll,Personnel
At this point we have a system that has several user accounts, each of which is mapped to an SELinux user identity. We have also established a number of categories that are suitable for the particular deployment, and assigned those categories to different users.
All of the files on the system, however, still fall under the same category, and are therefore accessible by everyone (but still according to the standard Linux DAC and TE constraints). We now need to assign categories to the various files on the system so that only the appropriate users can access them.
For this example, we create a file in Daniel's home directory:
[daniel@dhcp-133 ~]$ echo "Financial Records 2006" > financeRecords.txt
Use the ls -Z command to check the initial security context of the file:
[daniel@dhcp-133 ~]$ ls -Z financeRecords.txt -rw-r--r-- daniel daniel user_u:object_r:user_home_t financeRecords.txt
Notice that at this stage the file has the default context for a file created in the user's home directory (user_home_t) and has no categories assigned to it. We can add the required category using thechcat command. Now when you check the security context of the file, you can see the category has been applied.
[daniel@dhcp-133 ~]$ chcat -- +Finance financeRecords.txt [daniel@dhcp-133 ~]$ ls -Z financeRecords.txt -rw-r--r-- daniel daniel root:object_r:user_home_t:Finance financeRecords.txt
In many cases, you need to assign more than one category to a file. For example, some files may need to be accessible to users from both the Finance and Payroll departments.
[daniel@dhcp-133 ~]$ chcat -- +Payroll financeRecords.txt [daniel@dhcp-133 ~]$ ls -Z financeRecords.txt -rw-r--r-- daniel daniel root:object_r:user_home_t:Finance,Payroll financeRecords.txt
Each of the categories that have been assigned to the file are displayed in the security context. You can add and delete categories to files as required. Only users assigned to those categories can access that file, assuming that Linux DAC and TE permissions would already allow the access.
If a user who is assigned to a different category tries to access the file, they receive an error message:
[olga@dhcp-133 ~]$ cat financeRecords.txt cat: financeRecords.txt: Permission Denied
--------------------------------------
2. All about policies
In this section we'll discuss what policies are, what you can do with them, how they're created and how you make them take effect.2.1 What is a policy?
Policies are a set of rules governing things such as the roles a user has access to; which roles can enter which domains and which domains can access which types. You can edit your policy files according to how you want your system set up. The purpose of SE Linux is to enforce policies, so policies form the core of SE Linux. The default policy is to deny everything and every operation has to be explicitly permitted in a policy file.2.2 What can you do with policies?
Polices allow you the flexibility to configure your system as you wish. You may choose to have user A access both the user_r and sysadm_r roles, and have user B access the user_r role only. Policies can be as strict or as lenient as you require. Policies can also control what programs can do, and how programs can interact with each other such as controlling the accessing of files, programs tracing eachother, and sending signals. For example, with regard to accessing files you can have a policy for files created under /tmp so that one domain creates them, but another domain can't access them.2.3 How are policies created, and how do they take effect?
Policies must be compiled in to binary form before they can be used. In order to do this, you must run make in the policy directory, which is /etc/selinux/ for Debian and /etc/security/selinux/src/policy under Red Hat. The process of compiling the SE Linux policy is as follows:1) The policy configuration files are concatenated together. The policy configuration files end in .te and are found in the policy directory and subdirectories under that.
2) The m4 macro processor is applied to the result of the above concatenation, which then creates the policy.conf file. The policy.conf file is found in the policy directory, and contains things such as the definition of types, domains, rules for what each domain can do, roles, users, what roles users can access and lots of other stuff.
3) The checkpolicy policy compiler is run on policy.conf. This results in the creation of the policy.VERSION file, where VERSION is the version number. policy.VERSION is installed in to the /etc/security/selinux directory by running the command make install in the policy directory. This policy will then be loaded on the next reboot. If however, you wish to make a runtime change to your policy, you can run the command make load in the policy directory so that you can load the new policy in to a running kernel.
2.4 How are decisions made?
When you wish to perform a certain operation on a SE Linux system, your ability to do so is determined by your security context, the class of the object you're trying to access and the type of that object. For instance, a file has a class of file, a directory has a class of dir, and a Unix domain socket has a class of sock_file. The type of the object you're trying to access is predetermined by the policy. Let's say that as unprivileged user faye, I try to do ls -l /etc/shadow. Here is what gets logged (check the output of the dmesg command as sysadm_r) when I do this:avc: denied { getattr } for pid=10387 exe=/bin/ls path=/etc/shadow dev=03:03 ino=129766 \ scontext=faye:user_r:user_t tcontext=system_u:object_r:shadow_t tclass=fileThe Getting Started With SE Linux HOWTO document discussed these kinds of messages so I won't talk about them in depth here, instead I'll just talk about the bits relevant to this section. The source context (scontext) of the user running ls -l /etc/shadow is faye:user_r:user_t. So the identity is "faye" and I'm in the user_r role in the user_t domain. The target context (tcontext) is system_u:object_r:shadow_t so in other words, /etc/shadow has the type shadow_t. The class (tclass) of the target is file, so we know that /etc/shadow has a class of file. The entire avc message above shows my attempt to stat, or "getattr" /etc/shadow has failed.So where is it specified that /etc/shadow has the type shadow_t? The answer is in the file file_contexts under the directory file_contexts, which is under your policy source directory. If we grep for /etc/shadow in this file we see
/etc/shadow.* -- system_u:object_r:shadow_tThe specification for /etc/shadow's type is also found in the types.fc file, which is compiled to produce the file_contexts file. In this example, files called /etc/shadow.* have the system_u identity, as any files "owned" by the system have system_u. object_r is the role assigned to files, which doesn't mean all that much as roles are not relevant to files.3. policy.conf, checkpolicy, the Makefile
SE Linux has a number of configuration files which you will find yourself editing at some point. The next few sections will discuss the more commonly used and edited files.The main config file is policy.conf , located in your policy source directory. This file is comprised of the files ending in .te being joined together (see Section 2.3). In the normal course of operation you wouldn't edit policy.conf as it is automatically generated by running "make load", but you could edit it if you wanted to make a quick change such as doing a test.
Files that make up policy.conf will be discussed further on in this document.
3.1 checkpolicy
checkpolicy is the policy compiler, and is run during a "make reload" operation. checkpolicy's main task is to compile the policy, but you can also use it to query the policy. If I run checkpolicy as user_t I see:faye@kaos:/etc/selinux$ checkpolicy checkpolicy: loading policy configuration from policy.conf security: 4 users, 5 roles, 683 types security: 29 classes, 71806 rules checkpolicy: policy configuration loadedThis tells me I have four users, and in my /etc/selinux/users file they are faye, root, system_u and user_u. I have 5 roles which are user_r, sysadm_r, staff_r, and system_r. Where's the fifth role? Running the commandgrep ^role policy.conf | cut -f2 "-d "|sort -ushows I only have the four roles mentioned. The fifth role is object_r, which is the role assigned to all files, and is implicitly defined (it doesn't exist in the actual policy). Note that roles for files are not relevant and that if a file requires a level of protection, a specific type will be assigned to that file, such as shadow_t for /etc/shadow.The above example also shows I have 683 types (domains and types for files, directories and so forth), 29 classes (such as file, dir, unix_stream_socket and so on) and 71806 rules.
3.2 the Makefile
The Makefile in the policy source directory provides for the following operations to be performed:install
Running "make install" compiles and installs the policy, but does not load it. You would run this if you were not running an SE Linux kernel and wanted to install the policy so that when you next boot in to an SE Linux kernel, the policy would loaded.load
Running "make load" compiles, installs and then loads the policy configuration. You don't need to reboot your machine.reload
Running "make reload" compiles, installs and loads or reloads the policy configuration. When the Makefile loads a policy, a flag file called "load" is created in the tmp directory under your policy source directory. A "make load" won't do anything if this flag file exists AND you haven't changed anything more recently than the flag file's creation time, but you can reload.relabel
Running "make relabel" relabels filesystems based on the file contexts configuration. The file contexts configuration file is located in the file_contexts directory under your policy source directory.policy
Running "make policy" compiles the policy locally for testing/development. This results in the policy being compiled but not actually installed.4. Attributes: the attrib.te file
This section will discuss attributes, which are a way of grouping sets of types. The attrib.te file will be briefly examined. This file is located in your policy source directory, and contains attribute declarations for domains and types. Editing this file is not very common, however if you wanted to add a new attribute, you would edit it. The comments at the top of attrib.te state "a type attribute can be used to identify a set of types with a similar property. Each type can have any number of attributes, and each attribute can be associated with any number of types." Domains attributes are groupings of domains, just as attributes are groupings of types.Examples:
The domain attribute identifies every type that can be assigned to a process. This attribute refers to all processes that could be run, such as ps, top, inetd and so forth.The privuser attribute identifies every domain that can change its SELinux user identity. Note that we are talking about SE Linux user identity and not the standard Unix uid. Running the command grep ^type.*privuser policy.conf shows that the domains which can change their identity include sysadm_su_t, initrc_su_t, staff_su_t, run_init_t, local_login_t, remote_login_t, sshd_t, sshd_extern_t and xdm_t.
The privrole attribute identifies every domain that can change its SELinux role. A domain can spawn processes that have a different role. Take newrole for example. The point of newrole is to change to another role, so the privrole attribute needs to be assigned to newrole_t in order for this to happen. privrole only allows changing to other user roles. priv_system_role allows you to change to system_r.
The privowner attribute identifies every domain that can assign a different SELinux user identity to a file, or that can create a file with an identity that's not the same as the process identity. Using passwd_t as an example, the passwd_t process has the identity of the user running it, and it wants to relabel /etc/shadow with the system_u identity, thereby requiring privowner.
The userpty_type attribute identifies all non-administrative devpts types such as user_devpts_t and staff_devpts_t . For instance, if I run the command ls --context /dev/pts on my system, I will see
crw------- faye staff faye:object_r:staff_devpts_t 0 [snip]Here, /dev/pts/0 has the type staff_devpts_t .The sysadmfile attribute identifies all types assigned to files that should be completely accessible to administrators. Note that shadow_t is not by default accessible to administrators. It can be accessed by something like, for instance, setfiles, depending on what you're trying to do.
The fs_type attribute identifies all types assigned to filesystems (not limited to persistent filesystems). security_t applies to the /selinux filesystem in the new SE Linux.
The ptyfile attribute identifies all types assigned to ptys. The explanation for the ttyfile attribute also applies here, but with pty's. Running ls --context `tty` in an xterm would show the type of the pty device you are attached to, for e.g.
faye@kaos:/etc/selinux$ ls --context `tty` crw------- faye faye faye:object_r:user_devpts_t /dev/pts/1If I then switch to sysadm_r and run the same command, I seefaye@kaos:/etc/selinux$ newrole -r sysadm_r Authenticating faye. Password: faye@kaos:/etc/selinux$ id uid=1000(faye) gid=1000(faye) groups=1000(faye),20(dialout),25(floppy),29(audio),30(dip) \ context=faye:sysadm_r:sysadm_t faye@kaos:/etc/selinux$ ls --context `tty` crw------- faye faye faye:object_r:sysadm_devpts_t /dev/pts/1Note that my pty is now labelled with the type sysadm_devpts_t.The login_contexts attribute identifies the files used to define default contexts for login types (e.g., login, cron). Default context for login types are contained in the file /etc/security/default-contexts.
5. User related files
This section will discuss policy files related to actual users on the system, and where you can determine their level of access. In "Getting Started with SE Linux HOWTO" we saw that "an identity under SE Linux is not the same as the traditional Unix uid (user id). They can coexist together on the same system, but are quite different. identities under SE Linux form part of a security context which will affect what domains can be entered, i.e. what essentially can be done. An SE Linux identity and a standard Unix login name may have the same textual representation (and in most cases they do), however it is important to understand that they are two different things."5.1 The users file
The users file, found in your policy source directory for your distribution, such as /etc/selinux/users under Debian, contains definitions for each user that is to be recognised by your SE Linux system. If a user identity is explicitly named in this file, their user identity will form the first part of their security context. A security context is made up of the identity, role and domain or type. You can check your own current security context by running the id command under SE Linux. If a user identity is not named in the users file, they will be assigned the user_u identity.Following are some example entries in a users file.
user root roles { staff_r sysadm_r };This entry defines user identity root, and allows root to enter the staff_r and sysadm_r roles. The newrole command can be used to change user roles, or root (in this example) can choose to enter one of the roles above when logging in at the console.user faye roles { staff_r sysadm_r };Again, this entry defines the user identity faye. As with root, faye is also able to enter the sysadm_r role, which is the system administrator role. These two examples show you that the traditional root user does not necessarily have to have sysadm_r privileges just because they are user root, and that another user (such as faye) can have access to the system administrator role. If the roles definition for user root did not have sysadm_r, faye would be more powerful than root.user foo roles { user_r };User foo is defined, and they only have access to the user_r role, which is the general unprivileged user role.user system_u roles system_r;The system_u identity is the user identity for processes and objects such as files, directories, sockets and so on. You should not assign the system_u identity to a user process, as system_u is for daemons. If a user has system_u, they may potentially have access to the system_r role and any daemon domains.
5.2 The user.te file
This file is found in the subdirectory "domains" under your policy source directory, such as /etc/selinux/domains on Debian. user.te contains the unprivileged domains for the users on your SE Linux system. In this file you will see the linefull_user_role(user)This line allows all access necessary for the user role to do standard things such as run bin_t programs in their home directory, assign user_home_dir_t to the user's home directory and user_home_t to directories under that. The linesfull_user_role(staff) allow staff_t unpriv_userdomain:process signal_perms; can_ps(staff_t, unpriv_userdomain) allow staff_t { ttyfile ptyfile tty_device_t }:chr_file getattr;defines the domain staff_t. The second line allows the staff_t domain to send signals to processes running in unprivileged domains such as user_t and staff_t. The third line allows staff_t to run ps and see processes in the unprivileged user domains. staff_t is able to run ps and see everything in user_t and other user domains if any, whereas user_t can not. The fourth line allows staff_t to access the attributes of any terminal device.dontaudit unpriv_userdomain sysadm_home_dir_t:dir { getattr search };This line says not to audit unprivileged user domain (such as user_t) attempts to acces the /root directory by doing something like a ls -l or cd /root command, or trying to access a file under the /root directory. The line can also be read as "dontaudit source destination:destination class {what was attempted }".# change from role $1_r to $2_r and relabel tty appropriately define(`role_tty_type_change', ` allow $1_r $2_r; type_change $2_t $1_devpts_t:chr_file $2_devpts_t; type_change $2_t $1_tty_device_t:chr_file $2_tty_device_t; ')The first (uncommented) line defines the macro role_tty_type_change. This macro allows you to change roles and then relabel the tty you're using (such as when you use the newrole command to get from staff_r to sysadm_r and your tty changes). The second line says that $1_r is allowed to transition to $2_r (so $1_r might be staff_r and $2_r is sysadm_r). The relabelling of the tty is handled by the third and fourth lines.ifdef(`newrole.te', ` # # Allow the user roles to transition # into each other. role_tty_type_change(sysadm, user) role_tty_type_change(staff, sysadm) role_tty_type_change(sysadm, staff) ')This block says that if newrole.te is defined (i.e. if the file exists) then allow the roles shown to transition to eachother. These statements are the invocations of the role_tty_type_change macro as defined previously.5.3 The user_macros.te file
This file contains macros for user login domains which are domains users get upon logging in, as opposed to the domain of something like a cron job. Other non-login domains include those for gpg and irc, among others. I am using extracts of my own user_macros.te file as the example here (not the whole file). This file is located under the macros subdirectory of your policy source. I will break this file up in to little chunks for ease of explanation. Before I do that, I'd like to provide a brief definition of "capabilities": the ability to perform certain privileged operations.5.3.1 Macros for user login domains
-----
# user_domain() is also called by the admin_domain() macro undefine(`user_domain') define(`user_domain',`The above extract defines the macro user_domain-----
# Use capabilities allow $1_t self:capability { setgid chown fowner }; dontaudit $1_t self:capability { sys_nice fsetid };"Capabilities" in this snippet means the capability to change the group id (setgid). A program can call setgid() to change its group id, but only if it has the capability to do so in the first place, as well as not having given up the capability previously. A program can't call setgid() if this capability isn't granted. An in-depth discussion of capabilities is beyond the scope of this document, however please see /usr/include/linux/capability.h for more information. The first line allows the $1_t type the capability to setgid. $1 is the first parameter passed from the calling code (the code that called the macros). The second line says not to audit sys_nice (the ability to increase scheduling priority) or fsetid (related to controlling setuid and setgid files). These are capabilities requested repeatedly, so this line says not to audit the fact they're being requested.-----
# Type for home directory. ifelse($1, sysadm, ` type $1_home_dir_t, file_type, sysadmfile, home_dir_type, home_type; type $1_home_t, file_type, sysadmfile, home_type; tmp_domain($1) ', ` type $1_home_dir_t, file_type, sysadmfile, home_dir_type, user_home_dir_type, home_ type, user_home_type; type $1_home_t, file_type, sysadmfile, home_type, user_home_type;The above says that if $1 is sysadm then do the first block, otherwise do the second block, where both define types for home directories and tmp_domain (the macro for /tmp file access). So, the first block relates to sysadm stuff, and the second relates to the rest.# do not allow privhome access to sysadm_home_dir_t file_type_auto_trans(privhome, $1_home_dir_t, $1_home_t) tmp_domain($1, `, user_tmpfile') ')Here, we don't want privhome domains to access sysadm_home_dir_t. Take procmail for example. When procmail delivers mail it creates a file in a user's home directory. We don't want that happening to a sysadm directory (/root). "file_type_auto_trans" is the way to set the default type for a new file, otherwise it will be the same type as the directory it is created in. Normally when you create a file, it will have the same type as the directory it is created in. There are two ways to have a different type to that of the directory at creation time. The first is through open_secure() and the second is through file_type_auto_trans. For the first to be allowed, you need to have a file_type_trans rule that permits it, and then file_type_auto_trans makes it the default.-----
# allow ptrace can_ptrace($1_t, $1_t)This allows the first parameter ($1_t) to ptrace, or trace the process of the second parameter (also $1_t). This line therefore allows $1_t to ptrace itself.-----
# Create, access, and remove files in home directory. file_type_auto_trans($1_t, $1_home_dir_t, $1_home_t) allow $1_t $1_home_t:dir_file_class_set { relabelfrom relabelto };Here, a process in domain $1_t creates a file under a directory of type $1_home_dir_t and by default the created file is of type $1_home_t. The second line allows $1_t to relabel a file of type $1_home_t to something else, and to change the type from something else to $1_home_t.-----
# Bind to a Unix domain socket in /tmp. allow $1_t $1_tmp_t:unix_stream_socket name_bind;This allows $1_t to bind to a Unix domain socket, so it can then receive connections from other processes. $1_tmp_t is the type of the tmp_domain. name_bind allows $1_t to bind to a name under /tmp.5.3.2 Macros for ordinary user domains
Everything below refers to user_t.-----
undefine(`full_user_role') define(`full_user_role', ` # user_t/$1_t is an unprivileged users domain. type $1_t, domain, userdomain, unpriv_userdomain, web_client_domain; # $1_r is authorized for $1_t for the initial login domain. role $1_r types $1_t; allow system_r $1_r; # Grant permissions within the domain. general_domain_access($1_t);Define the macro full_user_role. Define the type $1_t/user_t and give it the four attributes listed. $1_r/user_r is able to have $1_t/user_t. system_r is then allowed access to $1_r/user_r. general_domain_access allows $1_t to see process in $1_t, see files in /proc/# among others (check the file core_macros.te).-----
# Read /etc. allow $1_t etc_t:dir r_dir_perms; allow $1_t etc_t:notdevfile_class_set r_file_perms; allow $1_t etc_runtime_t:{ file lnk_file } r_file_perms;Allow user_t to read etc_t (the type of /etc). You can see and read files under /etc and do things such as ls -l commands on /etc. If you look at the file core_macros.te you will see that notdevfile_class_set related to non-device file classes such as files, symlinks, socket files and fifo files. etc_runtime_t is the type for certain files in /etc (grep for "etc_runtime_t" in the file file_contexts).-----
undefine(`in_user_role') define(`in_user_role', ` role user_r types $1; role staff_r types $1; ')Define the macro in_user_role. A domain can be used in any of the user roles. The macro must be called in the .te file of the domain concerned. Look at the file passwd.te (for the passwd program). The in_user_role macro is invoked and has the passwd_t parameter passed to it. Going back to the above snippet, we can now sayrole user_r types passwd_t; role staff_r types passwd_t;meaning that user_r and staff_r can run the passwd program. Remember that if you add a new role, you must edit the in_user_role macro here.6. System administrator related files
This section will discuss the policies related to the sysadm_r role, i.e., the system administrator. We have already seen how an SE Linux identity can be granted sysadm_r in section 4.1.6.1 The admin_macros.te file
The admin_macros.te file contains macros for the system administration domains.-----
undefine(`admin_domain') define(`admin_domain',` # Inherit rules for ordinary users. user_domain($1)Define the macro admin_domain and allow it to have the same rules as user_t. $1 in this case would be sysadm.-----
allow $1_t policy_config_t:dir { getattr search }; allow $1_t policy_config_t:file getattr;Allow sysadm_t to getattr (things such as ls -l) and search files and directories under a directory that has a type of policy_config_t.-----
allow $1_t kernel_t:system syslog_read;Allow sysadm_t to read the system logs. kernel_t is the type for the kernel itself. system is the class of the operation, the operation being to read the syslog.-----
# Use capabilities other than sys_module. allow $1_t self:capability ~sys_module;Allow sysadm_t to use all capabilities apart from sys_module, which is used to load modules.-----
# Get security policy decisions. can_getsecurity($1_t)If you look at the file core_macros.te (under the macros directory) and search for can_getsecurity, this is what you see:# can_getsecurity(domain) # # Authorize a domain to get security policy decisions. # define(`can_getsecurity',` allow $1 security_t:dir { read search getattr }; allow $1 security_t:file { getattr read write }; allow $1 security_t:security { check_context compute_av compute_create compute_relabel compute_user }; ')Here, $1 is allowed to read, search and get attributes of a directory of type security_t (your policy source directory). $1 can also get attributes, read and write files in a directory of type security_t. Finally, $1 cancheck context validity, check whether the policy permits the source context to access the target context, compute a context for the labelling of a new object, compute the new context when relabelling an object, and to determine which user contexts can be reached from a given source context.-----
# Change system parameters. can_sysctl($1_t)sysadm_t is able to modify sysctl parameters, which is basically everything under /proc/sys. If you run the command grep ^type.*sysctl_type policy.conf you'll see the types that have the attribute sysctl_type.7. the file_contexts file
The file_contexts file contains security contexts which are applied to files on the system when a security policy installed. This file is read by the setfiles program and uses the information to label files. Below are some examples and explanations.# The security context for all files not otherwise specified. /.* system_u:object_r:file_tThis line sets the security context on files that do not have a specified context. system_u is the idenity for system processes and daemons and is the default identity for files owned by the system.# The root directory. / -d system_u:object_r:root_tSet the context with a type of root_t for the actual root directory (specified by the -d). /mnt and /initrd also have the type root_t./home/[^/]+ -d system_u:object_r:user_home_dir_t /home/[^/]+/.+ system_u:object_r:user_home_tFor the actual /home directory, set the type to user_home_dir_t. For files underneath it, set the type to user_home_t.You should be able to get a general understanding of everything else in this file, and it does help to have a good understanding of regular expressions.
In the middle column, you may see -- which refers to a regular file. -d refers to a directory. Nothing listed means anything is matched. If you do an "ls -l" command, the first character of the first column of output is what appears in the middle column. So if something was a symbolic link you'd see -l, -b for a block device and so forth.
8. the types directory
The types directory contains definitions of types, broken up in to the following files:8.1 device.te
This file contains the types for device nodes.type device_t, file_type;This line defines the type device_t for /dev. file_type is the attribute that is used for all types for files and directories. If you search for /dev in the file file_context you will see its type is set to device_t.type null_device_t, file_type, device_type, mlstrustedobject;Defines the type null_device_t for /dev/null. The device_type attribute identifies all types assigned to device nodes. mlstrustedobject is not used at this time.8.2 devpts.te
This file contains the types for pseudo ttys.type devpts_t, fs_type, root_dir_type;Set the type of the devpts filesystem (devpts_t) and the type of the root directory of that filesystem.8.3 file.te
This file contains the types for files.type unlabeled_t, sysadmfile;Unlabeled objects have the type unlabeled_t. Any time you change the policy to remove the definition of a type, everything that uses that type becomes unlabeled.8.4 network.te
This file contains the types for networking.type netif_t, netif_type; type netif_eth0_t, netif_type; type netif_eth1_t, netif_type; type netif_eth2_t, netif_type; type netif_lo_t, netif_type; type netif_ippp0_t, netif_type;The netif types are used for network interfaces.8.5 nfs.te
This file contains types for NFS usage.type nfs_t, fs_type, root_dir_type;nfs_t is the default type for NFS file systems and their files. Set the root directory of the NFS file system to be of type nfs_t.8.6 procfs.te
This file contains types for the proc file system.type proc_t, fs_type, root_dir_type; type proc_kmsg_t; type proc_kcore_t;proc_t is the type of the proc file system. proc_kmsg_t is the type for /proc/kmsg. proc_kcore_t is the type for /proc/kcore.8.7 security.te
This file contains types for security stuff for SE Linux.type security_t, fs_type; type policy_config_t, file_type; type policy_src_t, file_type;security_t is the target type when checking the permissions in the security class. policy_config_t is the type of /etc/security/selinux/* and policy_src_t is the type of /etc/selinux/* (on Debian).9. the macros directory
We've already covered the files user_macros.te and admin_macros.te. The two other files in the macros directory are core_macros.te and global_macros.te.9.1 core_macros.te
The core_macros.te file contains macros that are not changed very often, and it is recommended that you don't change them :) This is because core related policy should be the same if you want to share policy. Changing something in this file might render your policy incompatible with what everyone else is doing. Of course, if you don't care about anyone else, go ahead and change it. If you've changed your core_macros.te file, this may result in you having a system that works differently from everyone else, which may not be in your best interests.
Some of the macros contained in this file are macros for groupings of classes and permissions:
define(`dir_file_class_set', `{ dir file lnk_file sock_file fifo_file chr_file blk_file }')This line defines the macro dir_file_class_set which contains the classes dir (for directories), file (for files), lnk_file (for symbolic links), sock_file (for Unix domain sockets), fifo_file (for named pipes), chr_file (for character block devices) and blk_file (for block devices).define(`rw_file_perms', `{ ioctl read getattr lock write append }')This line defines the macros rw_file_perms which contains the permissions ioctl (for ioctl's), read (read file), getattr (get attributes) and then lock, write and append.9.2 global_macros.te
The global_macros.te file contains macros that are system wide, meaning they are not tied to particular policy files. You can edit this file if you want to, but it probably won't happen often.
define(`can_setexec',` allow $1 self:process setexec; allow $1 proc_t:dir search; allow $1 proc_t:{ file lnk_file } read; allow $1 self:dir search; allow $1 self:file { read write }; ')Defines the macro can_setexec. $1 is able to set the execute context, so it can set the context of a child process. $1 can search /proc and can read files and symlinks in that directory.9.3 the macros/program directory
The program subdirectory contains additional macros for programs that need per-user role policy. Programs such as ssh require a per-user role policy as the derived domains are based on the calling user domain. If you look at the filessh_macros.te you'll see
define(`ssh_domain',` # Derived domain based on the calling user domain and the program. type $1_ssh_t, domain, privlog;So if user_t was the calling user domain, the derived domain will be user_ssh_t. Likewise, if staff_t was the calling user domain, staff_ssh_t will be the derived domain. The linedomain_auto_trans($1_t, ssh_exec_t, $1_ssh_t)allows the transition from the calling domain to the derived domain.10. the flask directory
The flask directory contains the following files:access_vectors
This file defines the actions that can be performed for various classes. For the file class, you may perform actions such as read, write, link and so forth. For the socket class, you can perform actions like bind (for binding to a socket such as a TCP or UDP socket), listen (for incoming connections), connect and so on. Take a look through this file to familiarise yourself with the different actions various classes may perform.initial_sids
This file defines the initial SIDS (Security Identifiers). In the old SE Linux, SIDS were used in the userspace interface to the kernel. PSIDs (Persistent SIDs) were used in the kernel code for mapping files to contexts for files and directories on disk. See the NSA's document "Configuring the SELinux Policy" document for more information. In the new SE Linux, the extended attributes contain the context so SIDs and PSIDs are no longer necessary. Even though the new SE Linux uses extended attributes, some initial contexts still need to be defined when a system is started. The initial_sids file contains the initial SID contstants. The file initial_sid_contexts in your policy source directory maps these initial SIDS to contexts, and some examples follow:sid kernel system_u:system_r:kernel_t sid security system_u:object_r:security_tThe first line defines the initial SID of kernel, and gets the context of system_u:system_r:kernel_t . kernel_t is the type for general kernel code. The second line gives the sid security the context of system_u:object_r:security_t where security_t is the type for the /selinux file system.security_classes
This file defines the security object classes. These are the classes for things such as files and networking.An in-depth discussion of the Flask architecture is way beyond the scope of this document, but more information can be found in the NSA document "Configuring the SELinux Policy", particularly the section "Architectural Concepts and Definitions", at http://www.nsa.gov/selinux/doc/policy2/x34.html
11. Editing the policy
We'll now get in to the fun part of actually editing SE Linux policy. This takes a fair bit of practise. The best thing to do is just play around with it all. It can be quite a challenge to get started with as a lot of stuff isn't documented and you'll most likely take the trial-and-error approach. Make sure you look at other policies already written in /etc/selinux/domains/program/ and the corresponding file_contexts file in /etc/selinux/file_contexts/program/ .Here are some tips to keep in mind when you edit policy.
Work out what you want to change/edit.
Try to get a good understanding of what you're going to change. Is there some kind of action you want to allow, such as (for instance) allowing users in the user_r role to be able to see a certain directory not allowed in a default installation? What domain/s would be involved? What macros would you need to call? Look at existing rules to get an idea of syntax. Look up macros in the macros directory to get a feel for what they do.Create a file where you have custom rules.
I have a file called custom.te in the subdirectory domains/misc/ (under my policy source directory). In this file I include my own rules which are customised for what I want to do. Call this file something unique so that it won't get overwritten during an upgrade of the policy. custom.te should be fine. You can use this file to test stuff.Study the kernel messages.
If something isn't happening as you want it to, check out the kernel messages. A big part of writing policy is to study the logs then add or change rules to eliminate errors listed in the logs. If staff_t tries to run tcpdump and the operation is denied for instance, check the logs. You might see something likeavc: denied { create } for pid=17824 exe=/usr/bin/traceroute.lbl scontext=faye:staff_r:staff_t tcontext=faye :staff_r:staff_t tclass=rawip_socketHere we can see that someone in the staff_t domain tried to execute the traceroute command and was denied. From this log message we can work out that traceroute was running in the domain staff_t but we want it to run in a privileged domain that is able to traceroute. What we would need to do is edit our policy to allow staff_t to transition to traceroute_t (the domain for the traceroute process) when it executes the type traceroute_exec_t (which is the type of the actual traceroute executable, as opposed to the traceroute process that runs after you've executed the traceroute command).Comment the changes you make and why you made them.
Self explanatory :)12. Basic policy editing examples
Following are some examples of things you can try to get a feel for editing policy. Don't forget to run make load in your policy source directory after saving the policy file.12.1 Allow user_t to use tcpdump
If you haven't done so already, create a custom file (let's call it custom.te) in the subdirectory domains/misc/ under your policy source directory. Add the following lines:# your own comment here domain_auto_trans(userdomain, netutils_exec_t, netutils_t) in_user_role(netutils_t) allow netutils_t user:chr_file rw_file_perms;First of all, we need to be able to transition from the user domain (userdomain here refers to all possible user domains, so user_t, staff_t, sysadm_t and whatever other user domains you may have) to the domain for the actual tcpdump process, which is netutils_exec_t. What the first line is saying is "when the user domain runs the tcpdump executable, an automatic transition is made to the tcpdump process domain which is netutils_t".The in_user_role macro (defined in the file user_macros.te) permits the domain passed as a parameter (in this case netutils_t) to be in all the user roles (such as user_r and staff_r. sysadm_r is an administrative role, not a user role). This line is needed so that any combination of role user_r and domain netutils_t is valid in a security context.
The third line allows the domain netutils_t to access user pty types. netutils_t needs this access so that you can read from and write to your terminal device. chr_file is needed to write to the terminal device.
Exercise 1: Play around with these lines. Comment out the allow line, reload the policy and try to tcpdump. Check the logs to give you hints on why nothing seems to be happening.
Exercise 2: With the allow line commented out, switch to a virtual console (assuming you were using an xterm before) and try to tcpdump from there. If you have not specifically allowed tcpdump access from a tty device, try to make it happen. You should be able to tcpdump from a pty device, but not from a tty device so make the necessary changes and try again.
12.2 Allow user_t to read the /etc/selinux/ directory.
Ordinarily you probably don't want unprivileged users to see what's in /etc/selinux/ but for the sake of learning (assuming you're on a test machine playing around with SE Linux) I'll use this example. Edit your custom.te file to include the following:# your comment here r_dir_file(user_t,policy_src_t)The r_dir_file allows you to read a directory and files underneath it. user_t is the domain, and policy_src_t is the type of /etc/selinux .Exercise 1: try to access /etc/selinux before and after editing custom.te (and reloading the policy). Check the logs to see what's happening.
Exercise 2: from user_t try to access /boot. Got "permission denied"? Create a rule that allows user_t to read this directory.
12.3 Creating a new type
In this example we'll create a new file type for ourselves in custom.te so add the following lines and then run the make load command:type ourtype_t,file_type,sysadmfile; allow staff_t ourtype_t:file { create_file_perms relabelfrom relabelto };We define our new type called "ourtype_t", assign it the attribute file_type and sysadmfile so that the administrator can access it. The second line says that staff_t has full access to files of type ourtype_t (read, write and so forth). The relabelfrom and relabelto mean that staff_t can relabel files of type ourtype_t from and to another type.Now, in a staff_t role (I'm not going to tell you how to do that, read the Getting Started with SE Linux HOWTO) create a file. Check the security context of that file:
faye@kaos:~$ ls -Z foo -rw-r--r-- faye faye faye:object_r:staff_home_t fooSo we see file "foo" has the type staff_home_t. Now change that type to ourtype_t:faye@kaos:~$ chcon -t ourtype_t foo faye@kaos:~$ ls -Z foo -rw-r--r-- faye faye faye:object_r:ourtype_t fooNow let's remove the type we just created. Once again, edit your custom.te file to comment out what you just added. Run make load again, and try to look at the file's attributes:faye@kaos:~$ ls -Z foo ls: foo: Permission deniedAs sysadm_r run the same ls command:-rw-r--r-- faye faye faye:object_r:ourtype_t /home/faye/fooNow check your logs for the error that was logged when, as staff_r, you tried to access file foo:avc: denied { getattr } for pid=29494 exe=/bin/ls path=/home/faye/foo dev=md7 ino=145445 scontext=faye:staff _r:staff_t tcontext=system_u:object_r:unlabeled_t tclass=fileNote that the target context contains the type unlabeled_t for file foo. When we removed type ourtype_t from the policy, any files we created with that type are relabelled to type unlabeled_t. Note that even though ls -Z says the type is ourtype_t the kernel regards it as unlabeled_t as ourtype_t does not exist in the policy.13. Case study: the policy for INN
I will use the policy written for INN (InterNetNews server) to help you get a better idea of writing policy for an application. After you edit and save the policy file, run "make load" in your policy source directory to apply the changes.There are three files involved with the policy for INN. One is /etc/selinux/domains/program/innd.te . The second is the corresponding file_contexts file, /etc/selinux/file_contexts/program/innd.fc. The third is thenet_contexts file.
13.1 The innd.te file
Here is the entire policy. When you start writing policy, you can try and start the daemon. You'll get lots of messages in your logs, so you'll have to create rules to begin eliminating any "denied" messages. These give you clues as to what to do next.#DESC INN - InterNetNews server # # Author: Faye Coker <faye@lurking-grue.org> # X-Debian-Packages: inn # ################################ # Types for the server port and news spool. # type innd_port_t, port_type; type news_spool_t, file_type, sysadmfile; # need privmail attribute so innd can access system_mail_t daemon_domain(innd, `, privmail') # allow innd to create files and directories of type news_spool_t create_dir_file(innd_t, news_spool_t) # allow user domains to read files and directories these types r_dir_file(userdomain, { news_spool_t innd_var_lib_t innd_etc_t }) can_exec(initrc_t, innd_etc_t) can_exec(innd_t, { innd_exec_t bin_t }) ifdef(`hostname.te', ` can_exec(innd_t, hostname_exec_t) ') allow innd_t var_spool_t:dir { getattr search }; can_network(innd_t) can_unix_send( { innd_t sysadm_t }, { innd_t sysadm_t } ) allow innd_t self:unix_dgram_socket create_socket_perms; allow innd_t self:unix_stream_socket create_stream_socket_perms; can_unix_connect(innd_t, self) allow innd_t self:fifo_file rw_file_perms; allow innd_t innd_port_t:tcp_socket name_bind; allow innd_t self:capability { dac_override kill setgid setuid net_bind_service }; allow innd_t self:process setsched; allow innd_t { bin_t sbin_t }:dir search; allow innd_t usr_t:lnk_file read; allow innd_t usr_t:file { getattr read ioctl }; allow innd_t lib_t:file ioctl; allow innd_t { etc_t resolv_conf_t }:file { getattr read }; allow innd_t { proc_t etc_runtime_t }:file { getattr read }; allow innd_t urandom_device_t:chr_file read; allow innd_t innd_var_run_t:sock_file create_file_perms; # allow innd to read directories of type innd_etc_t (/etc/news/(/.*)? and symbolic links with that type etcdir_domain(innd) # allow innd to create files under /var/log of type innd_log_t and have a directory for its own files that # it can write to logdir_domain(innd) # allow innd read-write directory permissions to /var/lib/news. var_lib_domain(innd) ifdef(`crond.te', ` system_crond_entry(innd_exec_t, innd_t) ')The first step is to create the file. Because innd is a daemon listening on a port, we will need to create the type innd_port_t and assign it the port_type attribute (remember the attrib.te file?). We also know that a news spool is required, and we want to have a label assigned to the news spool files specific to INN. We call that type news_spool_t and give it the attributes of file_type and sysadmfile. sysadmfile is needed because we must grant access to the administrator domain to access those files with type news_spool_t. So from all this, we gettype innd_port_t, port_type; type news_spool_t, file_type, sysadmfile;Next, we need the macro daemon_domain() so that we can establish innd as a daemon with its own domain (which is innd_t). We need the attribute privmail because innd needs to be able to transition to the system_mail_t domain in order to send mail. Now we havedaemon_domain(innd, `, privmail')Above we created the type news_spool_t and now we want innd to be able to create the files and directories with that type. The create_dir_file() macro is needed for this so we havecreate_dir_file(innd_t, news_spool_t)which says that innd_t can create directories and files of type news_spool_t.We need our unprivileged users to be able to read the news spool files. We also need them to be able to read /var/lib/news/ which has been assigned the type innd_var_lib_t (see the innd.fc file), and we need them to be able to read /etc/news/ which has the type innd_etc_t. When these rules aren't plugged in, you'll get "avc denied" messages in your logs, so from there we work out what labels and rules are needed. Now we have
r_dir_file(userdomain, { news_spool_t innd_var_lib_t innd_etc_t })When starting up innd at this point, I received avc denied messages for initrc_d not being able to access innd_etc_t, and innd_t not being to access innd_exec_t and bin_t. We need the can_exec() macro here so that innd_t can execute programs of those types, giving uscan_exec(initrc_t, innd_etc_t) can_exec(innd_t, { innd_exec_t bin_t })An avc denied message in the logs was showing that innd_t could not access hostname_exec_t. We could put in a rule allowing innd_t to execute files of type hostname_exec_t but instead we take the following approach:ifdef(`hostname.te', ` can_exec(innd_t, hostname_exec_t) ')The ifdef line is used with the can_exec macro because if you don't name hostname.te in the policy, then there will be no type hostname_exec_t and the policy won't compile. We then use the can_exec() macro as before.We now want innd_t to be able to search and get the attributes of directories with the type var_spool_t and looking for var_spool_t which is the /var/spool directory.
allow innd_t var_spool_t:dir { getattr search };We know that innd_t will need network functionality so we need the following:can_network(innd_t)After that, we'll place all the network related stuff together to make for easier reading.can_unix_send( { innd_t sysadm_t }, { innd_t sysadm_t } )The can_unix_send() macro is used for sending Unix datagrams. In the line above we are saying "innd_t can send to and receive from itself and the sysadm_t domain, and sysadm_t can send to and receive from innd_t and itself".We now need innd_t to be able to create socket permissions in itself (that is, in its own domain of innd_t) so we add
allow innd_t self:unix_dgram_socket create_socket_perms; allow innd_t self:unix_stream_socket create_stream_socket_perms;innd_t will also need to be able to establish a stream connection to itself and for this we need the following macro and parameters:can_unix_connect(innd_t, self)innd_t will need read-write file permissions on anonymous pipes (created by the pipe() system call) in the innd_t domain. For this we includeallow innd_t self:fifo_file rw_file_perms;innd_t will need to bind to a tcp_socket so we needallow innd_t innd_port_t:tcp_socket name_bind;innd_t will need the following capabilities listed. See /usr/include/linux/capability.h for more information on what each capability does. innd_t will also need to be able to change the nice levels of innd processes.allow innd_t self:capability { dac_override kill setgid setuid net_bind_service }; allow innd_t self:process setsched;innd_t will need access to the listed domains. For the first allow rule below, innd_t will need to be able to search directories of types bin_t and sbin_t. For the second allow rule, innd_t will need read access to symbolic links of typeusr_t. When you have a getattr operation, include a read operation as well (as in the third, fifth and sixth allow rules below) because when you require getattr access, you'll almost certainly be needing read access too.allow innd_t { bin_t sbin_t }:dir search; allow innd_t usr_t:lnk_file read; allow innd_t usr_t:file { getattr read ioctl }; allow innd_t lib_t:file ioctl; allow innd_t { etc_t resolv_conf_t }:file { getattr read }; allow innd_t { proc_t etc_runtime_t }:file { getattr read }; allow innd_t urandom_device_t:chr_file read; allow innd_t innd_var_run_t:sock_file create_file_perms;innd_t will need to be able to read the /etc/news directory and files in it. innd_etc_t is the type assigned to /etc/news (see innd.fc). The file global_macros.te contains the macro definition for etcdir_domain, so read it to get a better idea of what it does. To our innd.te policy file we now addetcdir_domain(innd)innd_t will need to create log files under /var/log with a type of innd_var_log_t. It will need a directory of its own that it can write to. To achieve this, we needlogdir_domain(innd)innd_t will need read-write directory permissions to /var/lib/news so we includevar_lib_domain(innd)Lastly, we need the crond_t domain to be able to transition to innd_t when executing a program with the type innd_exec_t.ifdef(`crond.te', ` system_crond_entry(innd_exec_t, innd_t) ')13.2 the innd.fc file
The innd.fc file contains the file contexts we need to create for INN. These are the contents:/usr/sbin/innd.* -- system_u:object_r:innd_exec_t /var/run/innd(/.*)? system_u:object_r:innd_var_run_t /etc/news(/.*)? system_u:object_r:innd_etc_t /etc/news/boot -- system_u:object_r:innd_exec_t /var/spool/news(/.*)? system_u:object_r:news_spool_t /var/log/news(/.*)? system_u:object_r:innd_log_t /var/lib/news(/.*)? system_u:object_r:innd_var_lib_t /usr/sbin/in.nnrpd -- system_u:object_r:innd_exec_t /usr/lib/news/bin/.* -- system_u:object_r:innd_exec_t /usr/bin/inews -- system_u:object_r:innd_exec_t /usr/bin/rnews -- system_u:object_r:innd_exec_tOn the lefthand side of the file, we have the files and directories specific to INN. On the righthand side we assign the contexts. It is best to follow naming conventions at all times, such as appending _exec_t to the daemon name for executable files. In the middle of innd.fc we have -- which refers to regular files only. The entry for /etc/news(/.*)? can not contain -- because that directory contains subdirectories and does not consist solely of regular files.After saving your changes to this file, you need to apply the file contexts. From your policy source directory, run the following command to make the main file_contexts file so you can then relabel parts of the file system concerned with what you've specified in innd.fc :
make file_contexts/file_contextsIf you're not in the policy source directory, runmake -C file_contexts/file_contextsThe next step is to run the setfiles command to relabel each file or directory you have listed on the lefthand side. I'll take the first line of innd.fc as an example:setfiles -v file_contexts/file_contexts /usr/sbinAfter running this command, run a ls -Z command on /usr/sbin/innd.* to see that the relabelling has taken place.13.3 The net_contexts file
The net_contexts file in your policy source directory contains security contexts for network entities. The following line needs to be added to this file so that you are assigning tcp port 119 the type innd_port_t and no other type will be able to bind to that port.ifdef(`innd.te', `portcon tcp 119 system_u:object_r:innd_port_t')14. Policy tools
A number of tools have been developed for SE Linux. Some are listed below, with links to the appropriate tools. I have not played around with them much myself, but please visit the sites of the authors for more information.
Tresys Technologies: SE Linux Policy Tools
Tresys have developed tools for the analysis of the SE Linux policy, a GUI and command line tool to assist with managing your SE Linux system, a GUI tool to browse and modify policy components, a policy debugging application, a tool for viewing policy statistics and a tool to search TE (type enforcement) rules. Please visit http://www.tresys.com/selinux/selinux_policy_tools.html for more information.Mitre have developed a policy analysis tool, available at the NSA's SE Linux download site.
audit2allow was written by Justin R. Smith with contributions by Yuichi Nakamura and others not mentioned anywhere (apologies to those people). audit2allow takes the output of dmesg, analyses the avc denied messages and comes up with rules you can apply to fix those denied messages. It is included in the Debian package and Fedora rpm policycoreutils.
http://www.lurking-grue.org/writingselinuxpolicyHOWTO.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。