Read and Write SELinux Rules

This interface allows you to perform basic reading and standard writing operations on the system’s SELinux policies, enabling you to set or bypass certain system restrictions. These related interfaces may affect system functionality—please use them with caution. You should have a solid understanding of SELinux before using them.

Obtain an Operation Instance

Before getting started, you need to obtain a SELinux instance first.

selinux = d.stub("SelinuxPolicy")

Get SELinux Status

Use the following interface call to check whether SELinux is enabled.

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

Use the following interface call to get whether the current mode is enforcing.

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

Set SELinux Status

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

selinux.set_enforce(enable)

Use the following call to set SELinux to enforcing mode:

>>> selinux.set_enforce(True)
1

Use the following call to set SELinux to permissive mode:

>>> selinux.set_enforce(False)
0

Create 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

Set Domain to Permissive

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

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

Set Domain to Enforcing

Use the following interface call to set a 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 granular 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, respectively; tclass represents the object class; and action represents the specific operation. The action parameter only supports * (meaning all actions) or a specific single action. Multiple contexts or actions (such as {binder system_app}), which are allowed in standard SELinux rule syntax, are not supported here—you must provide only a single name for each parameter. Below are example usages.

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

The above rule means: allow hal_camera_default full permissions (all operations) on the directory (dir) camera_vendor_data_file. Similarly, replacing allow with disallow would deny these permissions.

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

You can also specify a finer-grained action like search, as shown above.