Reading and Writing SELinux Rules

This interface allows you to perform basic read and conventional write operations on the system's SELinux rules, enabling you to set or bypass some system restrictions. The related interfaces may affect system functionality, so please use them with caution. You need to have your own understanding of SELinux.

Getting an Operation Instance

Before you begin, you need to get an SELinux instance.

selinux = d.stub("SelinuxPolicy")

Getting SELinux Status

Use the following interface call to check if SELinux rules are enabled.

selinux.enabled()
>>> selinux.is_enabled( )
True

Use the following interface call to check if the current state is enforcing.

selinux.get_enforce()
>>> selinux.get_enforce()
1

Setting SELinux Status

Use the following interface call to set SELinux to enforcing or permissive mode.

selinux.set_enforce(enable)

Use the following interface call to set it to enforcing mode.

>>> selinux.set_enforce(True)
1

Use the following interface call to set it to permissive mode.

>>> selinux.set_enforce( False)
0

Creating a New Domain

Use the following interface call to create a new domain in SELinux.

selinux.create_domain(domain_name)
>>> selinux.create_domain("hello_selinux")
True

Setting a Domain to Permissive

Use the following interface call to set an SELinux domain to permissive mode.

selinux.permissive(domain_name)
>>> selinux.permissive("untrusted_app")
True

Setting a Domain to Enforcing

Use the following interface call to set an SELinux domain to enforcing mode.

selinux.enforce(domain_name)
>>> selinux.enforce("untrusted_app")
True

Fine-grained Control Rules

Use the following interface calls to write more fine-grained allow and disallow rules.

selinux.disallow(source, target, tclass, action)
selinux.allow(source, target, tclass, action)

Here, source and target represent the source and target contexts, tclass represents the target class, and action represents the specific operation. The action parameter only supports * (representing all) or a specific action. None of the parameters support multiple contexts or actions, such as the standard rule syntax {binder system_app}. Here, you can only provide a single name. Below is an example operation.

>>> selinux.allow("hal_camera_default", "camera_vendor_data_file", "dir", "*")

The rule above means to grant hal_camera_default all operation permissions on the camera_vendor_data_file directory (dir). Similarly, changing the method to disallow would deny these permissions.

>>> selinux.allow("hal_camera_default", "camera_vendor_data_file", "dir", "search")

You can also provide a fine-grained action like search as shown above.