SELinux - Arch Linux 中文维基

跳至內容

# SELinux

出自 Arch Linux 中文维基

這篇文章或章節的翻譯質量不佳。

原因：似乎為機翻，亟需校對潤色。（在 Talk:SELinux# 中討論）

本文或本節需要翻譯。要貢獻翻譯，請訪問簡體中文翻譯團隊。

附註： 部分章節未翻譯。（在 Talk:SELinux# 中討論）

相關文章

- Security
- AppArmor
- TOMOYO Linux

安全增強型 Linux（SELinux）是一項 Linux 功能，通過在 Linux 內核中使用 Linux 安全模塊（LSM）提供各種安全策略，包括美國國防部風格的強制訪問控制（MAC）。它並不是一個 Linux 發行版，而是一組可以應用於類 Unix 作業系統，如 Linux 和 BSD 的修改。

在 Linux 發行版下運行 SELinux 需要三個要素：啟用 SELinux 的內核、SELinux 用戶空間工具和庫，以及 SELinux 策略（大部分基於參考策略）。一些常見的 Linux 程序還需要進行修補/編譯以支持 SELinux 功能。

## 在 Arch Linux 中的當前狀態是怎樣的？

SELinux 並不是 Arch Linux 官方支持的功能（參見這裡[1]和這裡[2]）。非官方支持的狀態如下：

名稱 | 狀態 | 可用地址
--- | --- | ---
SELinux 啟用的內核 | 為所有官方支持的內核實施 | 自 4.18.8 版本以來已在官方倉庫中提供
SELinux 用戶空間工具和庫 | 在 AUR 中實施：https://aur.archlinux.org/packages/?O=0&K=selinux | 工作正在 https://github.com/archlinuxhardened/selinux 進行
SELinux 策略 | 工作進行中，使用 Reference Policy 作為上游源 | 上游源：https://github.com/SELinuxProject/refpolicy（自 20170805 版本以來，該策略已經整合了對 systemd 和單一-/usr/bin 目錄的支持）

與官方核心包相比，以下是 AUR 中的一些包的變更摘要：

名稱 | 狀態和評論
--- | ---
linux, linux-lts, linux-zen, linux-hardened | 需要設置 lsm= 內核參數
coreutils | 需要使用 `--with-selinux` 標誌重新構建以連結 libselinux
cronie | 需要使用 `--with-selinux` 標誌重新構建
dbus | 需要使用 `--enable-libaudit` 和 `--enable-selinux` 標誌重新構建
findutils | 需要安裝 libselinux 並重新構建以啟用 SELinux 特定選項
iproute2 | 需要使用 `--with-selinux` 標誌重新構建
logrotate | 需要使用 `--with-selinux` 標誌重新構建
openssh | 需要使用 `--with-selinux` 標誌重新構建
pam | 對於 Linux-PAM，需要使用 `--enable-selinux` 標誌重新構建；還需要一個用於 pam_unix2 的補丁，該補丁僅刪除最近版本的 libselinux 中已實現的一個函數
pambase | 需要進行配置更改，將 pam_selinux.so 添加到 `/etc/pam.d/system-login`
psmisc | 需要使用 `--with-selinux` 標誌重新構建
shadow | 需要使用 `--with-selinux` 標誌重新構建
sudo | 需要使用 `--with-selinux` 標誌重新構建
systemd | 需要使用 `--enable-audit` 和 `--enable-selinux` 標誌重新構建
util-linux | 需要使用 `--with-selinux` 標誌重新構建

這些 SELinux 相關的包中的其他包可以無需更改或風險地包括在內。

## 概念：強制訪問控制

注意：本節面向初學者。如果您了解SELinux的工作原理和功能，請隨時跳到安裝部分。

在啟用SELinux之前，值得先了解它的工作原理。簡而言之，SELinux在Linux上執行強制訪問控制（MAC）。與SELinux相比，傳統的用戶/組/rwx權限是一種自主訪問控制（DAC）形式。MAC與DAC不同，因為安全策略及其執行是完全分離的。

一個例子是使用sudo命令。當執行DAC時，sudo允許臨時提權到root，使所生成的進程具有無限制的系統範圍訪問權限。但是，當使用MACs時，如果安全管理員認為該進程只能訪問某個文件集合，那麼無論使用何種類型的特權提升，除非更改安全策略本身，否則該進程將保持約束在該文件集合中。因此，如果在運行SELinux的機器上嘗試使用sudo以使進程能夠訪問其策略不允許的文件，將會失敗。

另一組示例是對文件授予的傳統(-rwxr-xr-x)類型權限。在DAC下，這些權限是可由用戶修改的。但是，在MAC下，安全管理員可以選擇凍結某個文件的權限，從而使任何用戶都無法更改這些權限，直到有關該文件的策略發生更改。

正如您所想像的那樣，這對於具有被攻擊潛力的進程非常有用，例如Web伺服器等。如果使用DAC，那麼受損的程序具有特權提升的訪問權限，可能會造成嚴重破壞的可能性很高。

欲了解更多信息，請訪問Wikipedia:Mandatory access control。

## Installing SELinux

### Package description

All SELinux related packages belong to the selinux group in the AUR. Before you manually install any of these, read #Installation to see recommended options for a comprehensive installation.

#### SELinux aware system utilities

coreutils-selinuxAUR
  Modified coreutils package compiled with SELinux support enabled. It replaces the coreutils包 package
cronie-selinuxAUR
  Fedora fork of Vixie cron with SELinux enabled. It replaces the cronie包 package.
dbus-selinuxAUR
  An SELinux aware version of D-Bus. It replaces the dbus包 package.
findutils-selinuxAUR
  Patched findutils package compiled with SELinux support to make searching of files with specified security context possible. It replaces the findutils包 package.
iproute2-selinuxAUR
  iproute2 package compiled with SELinux support; for example, it adds the `-Z` option to `ss`. It replaces the iproute2包 package.
logrotate-selinuxAUR
  Logrotate package compiled with SELinux support. It replaces the logrotate包 package.
openssh-selinuxAUR
  OpenSSH package compiled with SELinux support to set security context for user sessions. It replaces the openssh包 package.
pam-selinuxAUR and pambase-selinuxAUR
  PAM package with pam_selinux.so. and the underlying base package. They replace the pam包 and pambase包 packages respectively.
psmisc-selinuxAUR
  Psmisc package compiled with SELinux support; for example, it adds the `-Z` option to `killall`. It replaces the psmisc包 package.
shadow-selinuxAUR
  Shadow package compiled with SELinux support; contains a modified `/etc/pam.d/login` file to set correct security context for user after login. It replaces the shadow包 package.
sudo-selinuxAUR
  Modified sudo package compiled with SELinux support which sets the security context correctly. It replaces the sudo包 package.
systemd-selinuxAUR
  An SELinux aware version of Systemd. It replaces the systemd包 package.
util-linux-selinuxAUR
  Modified util-linux package compiled with SELinux support enabled. It replaces the util-linux包 package.

#### SELinux userspace utilities

checkpolicyAUR
  Tools to build SELinux policy
mcstransAUR
  Daemon which is used by libselinux to translate MCS labels
libselinuxAUR
  Library for security-aware applications. Python bindings needed for semanage and setools now included.
libsemanageAUR
  Library for policy management. Python bindings needed for semanage and setools now included.
libsepolAUR
  Library for binary policy manipulation.
policycoreutilsAUR
  SELinux core utils such as newrole, setfiles, etc.
restorecondAUR
  Daemon which maintains the label of some files
secilcAUR
  Compiler for SELinux policies written in CIL (Common Intermediate Language)
selinux-dbus-configAUR
  DBus service which allows managing SELinux configuration
selinux-guiAUR
  SELinux GUI tools (system-config-selinux)
selinux-pythonAUR and selinux-python2AUR
  SELinux python tools and libraries (semanage, sepolgen, sepolicy, etc.)
selinux-sandboxAUR
  Sandboxing tool for SELinux
semodule-utilsAUR
  Tools to handle SELinux modules when building a policy

#### SELinux policy packages

selinux-refpolicy-srcAUR
  Reference policy sources
selinux-refpolicy-gitAUR
  Reference policy git master (https://github.com/SELinuxProject/refpolicy) built with configuration specific for Arch Linux
selinux-refpolicy-archAUR
  Precompiled modular Reference policy with headers and documentation but without sources. Development Arch Linux Refpolicy patches included, which fixes issues related to path labeling and systemd support. These patches are also sent to Reference Policy maintainers and their inclusion in selinux-refpolicy-archAUR is mainly a way to perform updates between Refpolicy releases.

#### Other SELinux tools

setoolsAUR
  CLI and GUI tools to manage SELinux
selinux-alpm-hookAUR
  pacman hook to label files accordingly to SELinux policy when installing and updating packages

### Installation

There are three methods to install the requisite SELinux packages.

#### Via binary package on GitHub

All packages are available from the selinux unofficial repository. the base package can be replaced with base-selinux during the `arch-bootstrap` stage of system installation.

警告：Currently this repository does not provide signed packages, meaning that the binary it downloads will not be verified by pacman. This presents a security risk; proceed with caution

#### Via build script from GitHub

This repository also contains a script named `build_and_install_all.sh` which builds and installs (or updates) all packages in the needed order. Here is an example of a way this script can be used in a user shell to install all packages (with downloading the GPG keys which are used to verify the source tarballs of the package):

    $ git clone https://github.com/archlinuxhardened/selinux.git
    $ cd selinux
    $ ./recv_gpg_keys.sh
    $ ./build_and_install_all.sh

Of course, it is possible to modify the content of `build_and_install_all.sh` before running it, for example if you already have SELinux support in your kernel.

#### Via AUR

- First, install SELinux userspace tools and libraries, in this order (because of the dependencies): libsepolAUR, libselinuxAUR, checkpolicyAUR, secilcAUR, setoolsAUR, libsemanageAUR, semodule-utilsAUR, policycoreutilsAUR, selinux-pythonAUR (which depends on python-ipy包), mcstransAUR and restorecondAUR.
- Then install pambase-selinuxAUR and pam-selinuxAUR and make sure you can login again after the installation completed, because files in `/etc/pam.d/` got removed and created when pambase包 got replaced with pambase-selinuxAUR.
- Next you can recompile some core packages by installing: coreutils-selinuxAUR, findutils-selinuxAUR, iproute2-selinuxAUR, logrotate-selinuxAUR, openssh-selinuxAUR, psmisc-selinuxAUR, shadow-selinuxAUR, cronie-selinuxAUR
- Next, backup your `/etc/sudoers` file. Install sudo-selinuxAUR and restore your `/etc/sudoers` (it is overridden when this package is installed as a replacement of sudo包).
- Next come util-linux and systemd. Because of a cyclic makedepends between these two packages which will not be fixed (FS#39767), you need to build the source package systemd-selinuxAUR, install systemd-libs-selinuxAUR, build and install util-linux-selinuxAUR (with util-linux-libs-selinuxAUR) and rebuild and install systemd-selinuxAUR.
- Next, install dbus-selinuxAUR.
- Next, install selinux-alpm-hookAUR in order to run restorecon every time pacman installs a package.

After all these steps, you can install a SELinux kernel (like linux包) and a policy (like selinux-refpolicy-archAUR or selinux-refpolicy-gitAUR).

### Enable SELinux LSM

To enable SELinux as default security model on every boot, set the following kernel parameter:

    lsm=landlock,lockdown,yama,integrity,selinux,bpf

注意：The `lsm=` kernel parameter sets the initialization order of Linux security modules. The kernel's configured `lsm=` value can be found with `zgrep CONFIG_LSM= /proc/config.gz` and the current value with `cat /sys/kernel/security/lsm`.

- Make sure that `selinux` is the first "major" module in the list.[1] Examples of valid values and their order can be found in security/Kconfig.
- `capability` should be omitted from `lsm=` as it will always get included automatically.

#### Custom kernel

When compiling the kernel, it is required to set at least the following options:

    CONFIG_SECURITY_SELINUX=y
    CONFIG_AUDIT=y

To enable the SELinux Linux security model by default and omit the need to set kernel parameters, additionally set the `CONFIG_LSM` option and specify `selinux` as the first "major" module in the list:

    CONFIG_LSM="landlock,lockdown,yama,integrity,selinux,bpf"

### Checking PAM

A correctly set-up PAM is important to get the proper security context after login. Check for the presence of the following lines in `/etc/pam.d/system-login`:

    # pam_selinux.so close should be the first session rule
    session         required        pam_selinux.so close

    # pam_selinux.so open should only be followed by sessions to be executed in the user context
    session         required        pam_selinux.so open

### Installing a policy

警告：The reference policy as given by SELinuxProject is not very good for Arch Linux. Most people submitting patches to improve the policy use an other distribution (Debian, Gentoo, RHEL, etc.), therefore the compatibility with Arch Linux packages is not perfect (for example the policy may not support the most recent features of a program).

Policies are the mainstay of SELinux. They are what govern its behaviour. The only policy currently available in the AUR is the Reference Policy. In order to install it, you should use the source files, which may be got from the package selinux-refpolicy-srcAUR or by downloading the latest release on https://github.com/SELinuxProject/refpolicy/wiki/DownloadRelease#current-release. When using the AUR package, navigate to `/etc/selinux/refpolicy/src/policy` and run the following commands:

    # make bare
    # make conf
    # make install

to install the reference policy as it is. Those who know how to write SELinux policies can tweak them to their heart's content before running the commands written above. The command takes a while to do its job and taxes one core of your system completely, so do not worry. Just sit back and let the command run for as long as it takes.

To load the reference policy run:

    # make load

Then, make the file `/etc/selinux/config` with the following contents (Only works if you used the defaults as mentioned above. If you decided to change the name of the policy, you need to tweak the file):

    /etc/selinux/config

    # This file controls the state of SELinux on the system.
    # SELINUX= can take one of these three values:
    #       enforcing - SELinux security policy is enforced.
    #                   Set this value once you know for sure that SELinux is configured the way you like it and that your system is ready for deployment
    #       permissive - SELinux prints warnings instead of enforcing.
    #                    Use this to customise your SELinux policies and booleans prior to deployment. Recommended during policy development.
    #       disabled - No SELinux policy is loaded.
    #                  This is not a recommended setting, for it may cause problems with file labelling
    SELINUX=permissive
    # SELINUXTYPE= takes the name of SELinux policy to
    # be used. Current options are:
    #       refpolicy (vanilla reference policy)
    #       <custompolicy> - Substitute <custompolicy> with the name of any custom policy you choose to load
    SELINUXTYPE=refpolicy

Now, you may reboot. After rebooting, run:

    # restorecon -r /

to label your filesystem.

Now, make a file `requiredmod.te` with the contents:

    requiredmod.te

    module requiredmod 1.0;

    require {
            type devpts_t;
            type kernel_t;
            type device_t;
            type var_run_t;
            type udev_t;
            type hugetlbfs_t;
            type udev_tbl_t;
            type tmpfs_t;
            class sock_file write;
            class unix_stream_socket { read write ioctl };
            class capability2 block_suspend;
            class dir { write add_name };
            class filesystem associate;
    }

    #============= devpts_t ==============
    allow devpts_t device_t:filesystem associate;

    #============= hugetlbfs_t ==============
    allow hugetlbfs_t device_t:filesystem associate;

    #============= kernel_t ==============
    allow kernel_t self:capability2 block_suspend;

    #============= tmpfs_t ==============
    allow tmpfs_t device_t:filesystem associate;

    #============= udev_t ==============
    allow udev_t kernel_t:unix_stream_socket { read write ioctl };
    allow udev_t udev_tbl_t:dir { write add_name };
    allow udev_t var_run_t:sock_file write;

and run the following commands:

    # checkmodule -m -o requiredmod.mod requiredmod.te

    semodule_package -o requiredmod.pp -m requiredmod.mod
    semodule -i requiredmod.pp

This is required to remove a few messages from `/var/log/audit/audit.log` which are a nuisance to deal with in the reference policy. This is an ugly hack and it should be made very clear that the policy so installed simply patches the reference policy in order to hide the effects of incorrect labelling.

### Testing in a Vagrant virtual machine

It is possible to use Vagrant to provision a virtual Arch Linux machine with SELinux configured. This is a convenient way to test an Arch Linux system running SELinux without modifying a current system. Here are commands which can be used to achieve this:

    $ git clone https://github.com/archlinuxhardened/selinux.git
    $ cd selinux/_vagrant
    $ vagrant up
    $ vagrant ssh

## Post-installation steps

You can check that SELinux is working with `sestatus`. You should get something like:

    SELinux status:                 enabled
    SELinuxfs mount:                /sys/fs/selinux
    SELinux root directory:         /etc/selinux
    Loaded policy name:             refpolicy
    Current mode:                   permissive
    Mode from config file:          permissive
    Policy MLS status:              disabled
    Policy deny_unknown status:     allowed
    Max kernel policy version:      28

To maintain correct context, you can enable `restorecond.service`.

To switch to enforcing mode without rebooting, you can use:

    # echo 1 > /sys/fs/selinux/enforce

### Swapfiles

If you have a swap file instead of a swap partition, issue the following commands in order to set the appropriate security context:

    # semanage fcontext -a -t swapfile_t "/path/to/swapfile"
    # restorecon /path/to/swapfile

## Working with SELinux

SELinux defines security using a different mechanism than traditional Unix access controls. The best way to understand it is by example. For example, the SELinux security context of the apache homepage looks like the following:

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

    -rw-r--r--  username username system_u:object_r:httpd_sys_content_t /var/www/html/index.html

The first three and the last columns should be familiar to any (Arch) Linux user. The fourth column is new and has the format:

    user:role:type[:level]

To explain:

1. User: The SELinux user identity. This can be associated to one or more roles that the SELinux user is allowed to use.
2. Role: The SELinux role. This can be associated to one or more types the SELinux user is allowed to access.
3. Type: When a type is associated with a process, it defines what processes (or domains) the SELinux user (the subject) can access. When a type is associated with an object, it defines what access permissions the SELinux user has to that object.
4. Level: This optional field can also be know as a range and is only present if the policy supports MCS or MLS.

This is important in case you wish to understand how to build your own policies, for these are the basic building blocks of SELinux. However, for most purposes, there is no need to, for the reference policy is sufficiently mature. However, if you are a power user or someone with very specific needs, then it might be ideal for you to learn how to make your own SELinux policies.

This is a great series of articles for someone seeking to understand how to work with SELinux.

## Troubleshooting

The place to look for SELinux errors is the systemd journal. In order to see SELinux messages related to the label `system_u:system_r:policykit_t:s0` (for example), you would need to run:

    # journalctl _SELINUX_CONTEXT=system_u:system_r:policykit_t:s0

### Useful tools

There are some tools/commands that can greatly help with SELinux.

restorecon
  Restores the context of a file/directory (or recursively with `-R`) based on any policy rules
chcon
  Change the context on a specific file

### Reporting issues

Please report issues on GitHub: https://github.com/archlinuxhardened/selinux/issues

## See also

- Security Enhanced Linux
- Gentoo:SELinux
- Fedora:SELinux
- NSA's Official SELinux Homepage
- SELinux Project Homepage
  - Reference Policy Homepage
  - SETools Homepage
- ArchLinux, SELinux and You (archived)

## 參考資料

1. ↑ https://lists.archlinux.org/archives/list/arch-general@lists.archlinux.org/message/4LXUXQSFEPVLN7S2DDBIGVUS7L7ES5S2/
2. ↑ https://lists.archlinux.org/archives/list/arch-general@lists.archlinux.org/message/VM72SI36VDX4PVUP4ZZEDIOSBVYTI7OG/

隱藏分類：​

- 使用「模板:糟糕的翻譯」標記的頁面或章節
- 使用「模板:Translateme」標記的頁面或章節

SELinux
新增話題