I. Background
SEAndroid
is a set of security mechanisms applied by Google on the Android system based onSELinux
as the core system security mechanism (hereinafter referred to as SELinux). It was first released in Android 4.3, and after many years of development, it has become an important guarantee for user-space security in Android.
In recent security research, the No恒 Laboratory has focused onSELinux
Some research results on the attack surface and attack methods of SELinux are shared here, hoping to engage in learning and exchange with the industry.

SELinux (Security-Enhanced Linux)
is a Linux kernel security module led by the National Security Agency (NSA), which providesMandatory Access Control (MAC)
It was released to the open source community in 2000 and integrated into the upstream Linux kernel in 2003. 'So, an excellent security mechanism is to disclose all details while still keeping attackers at bay :)'
The default access control strategy of Linux isDiscretionary Access Control (DAC)
The following two figures can be used to intuitively understand the difference between DAC and MAC:
The image source is https://blog.csdn.net/headwind_/article/details/119704755
InDAC
in, the owner of the object can arbitrarily modify or grant the corresponding permissions to this object, and theoretically, the permissions owned by the process are the same as those of the user executing it; this leads to ifroot
the process with permission is attacked, the attacker can take advantage of this to freely operate in the system.
inMAC
In it, security contexts are set for all processes and files. When a user performs an operation, in addition to passingDAC
inspection, it still needs to comply withMAC
rules; Therefore, even ifroot
process, and their permissions will also be restricted to a specific range. Although this cannot completely prevent attacks, it can reduce the loss to the lowest possible level.
2. Implementation of SELinux
The implementation of SELinux depends on theSecurity Module Framework (LSM)
When the kernel handles user-space access, LPM reserves a hook function after DAC checking, and SELinux implements MAC through this interface; therefore, the permissions on the Android platform areDAC+MAC
That is, two permission management mechanisms exist independently, and operation behaviors must pass the inspection of both mechanisms to be allowed.
https://www.kernel.org/doc/ols/2002/ols2002-pages-604-617.pdf
3. Basic Elements
3.1 Tag
SElinux
is a tagging-based system, and all processes, files, sockets, etc. have tags. A tag is a four-tuple stringuser:role:type:level
Among them, we mainly focus ontype
.
In the Android system, all objects can be roughly divided into two categories:
One is
Dead
of (files, ports, system properties, etc. that are called), for example:u:object_r:proc:s0
One is
Live
of (processes, Apps, etc. that call resources), for example:u:r:vendor_init:s0
The method to view labels is to add -Z to the commonly used commands, as follows:
process ps -ZAu:r:vendor_init:s0 root 545 1 6728 2376 poll_sche+ 0 S init
u:r:zygote:s0 root 678 1 4308756 142888 poll_sche+ 0 S zygote64
file ls -lZdrwxr-x--- 2 root shell u:object_r:rootfs:s0 4096 2009-01-01 00:00 sbin
drwxr-xr-x 18 root root u:object_r:vendor_file:s0 4096 2009-01-01 00:00 vendor
attribute getprop -Z [DEVICE_PROVISIONED]: [u:object_r:default_prop:s0]
[aaudio.hw_burst_min_usec]: [u:object_r:exported_default_prop:s0]
3.2 Rule
Withlabels
After that, you need to writerules
to limit labels. According to SELinux specifications, the complete statement format for rules is as follows:
rule_name source_type target_type:class perm_set
rule_name rule name
allow
: Allows the subject to perform operations on the objectneverallow
: Refuses the subject to perform operations on the objectdontaudit
: Indicates that information about a violation of the rule is not recordedauditallow
: Records information about a decision, usually SELinux only records failed information. Applying this rule will record successful decision information
source_type subject
Domain
: A label of a process or a set of processes. Also known as domain type
target_type entity
Type
: A label of an object (such as, file, socket) or a set of objects
class category
The type of object to be accessed, such as files, sockets, etc.
In
system/sepolicy/private/security_classes
is defined in
perm_set action set
operations to be performed, such as read, write, etc.
In
system/sepolicy/private/access_vectors
is defined in
Below is an example to illustrate:
# Allows processes in the user domain to read file type files in the script label
allow user script:file {read};
# Does not allow processes in the user domain to write to file type files in the script label
neverallow user script:file {write};
3.3 Configuration File
compiled by SELinuxlabels
andrules
Files such as these will be saved in the rule of each partition:etc/selinux
The directory below:
$ls -l system/etc/selinux
drwxrwxr-x 2 root root 4096 Dec 9 15:53 mapping/
-rw-rw-r-- 1 root root 40561 Dec 10 15:56 plat_file_contexts
-rw-rw-r-- 1 root root 8614 Dec 10 15:56 plat_hwservice_contexts
-rw-rw-r-- 1 root root 7243 Dec 9 15:53 plat_mac_permissions.xml
-rw-rw-r-- 1 root root 48646 Dec 10 15:56 plat_property_contexts
-rw-rw-r-- 1 root root 1905 Dec 10 15:56 plat_seapp_contexts
-rw-rw-r-- 1 root root 65 Dec 10 15:55 plat_sepolicy_and_mapping.sha256
-rw-rw-r-- 1 root root 1623615 Dec 10 15:55 plat_sepolicy.cil
-rw-rw-r-- 1 root root 19798 Dec 10 15:56 plat_service_contexts
-rw-rw-r-- 1 root root 818418 Dec 10 15:55 sepolicy_neverallows
Among themplat_sepolicy.cil
records SELinux rules,plat_sepolicy_and_mapping.sha256
To verify files, the rest of the files record are tag data.
Four, SEAndroid security risks
SELinux achieves the purpose of converging the attack surface and reducing losses by maximizing the restriction of the resources that service processes can access in the system; however, it is not omnipotent. Issues such as debugging interfaces left by development, kernel vulnerabilities, and incorrect strategy configurations can all lead to attackers bypassing SELinux's restrictions and attacking the system.
4.1 Custom backdoor
As the saying goes, 'The enemy is in the本能寺', some manufacturers may reserve a way to shut down SELinux for convenience during development to facilitate debugging.Backdoor interface
, if suchBackdoor
Before formal release, if not deleted, it may be exploited by attackers to shut down SELinux.
4.2 Kernel Vulnerability
SELinux mainly limits user-space operations. If an attacker gains the ability to read and write any address through kernel vulnerabilities, they can overwrite global variablesselinux_enforcing
method to disable SELinux.
For this reason, Samsung uses its self-developedRKP(Real-time Kernel Protection)
mechanism, placing sensitive global variables in the protectedkdp_ro section
to some extent mitigates such attacks.
4.3 Policy Too Broad
SELinux also existspeople
the issues introduced, ifsensitive services
opened to ordinary users, or forSystem APP
,Property
The permission division is not detailed, which can lead to a wider range of impact when attacked.
4.4 Service Function and SELinux Policy Misalignment
In the Android system, some areas need to write various data frequently, such as/data/local/tmp
,/sdcard
etc., therefore SELinux does not impose strict restrictions on these locations, and normal user permissions can read and write the data within them.
In principle, these directories should not store sensitive data. If R&D personnel store some important files in these directories (such as configuration files, privacy information, firmware upgrades, etc.), there is a risk of being stolen or tampered with by attackers.
5. SEAndroid Disable Methods
The methods introduced above are ways to bypass SELinux at runtime, but in daily work, there is also such a scenario where we need to obtain Root permissions on an unlocked Android device for testing; there are some excellent Root tools on high-version Android, such asMagisk
,KernelSU
etc., but using automated tools can never fully understand the underlying principles. If you want to manually ROOT the device, disabling SELinux is a crucial step. Below are several methods for manually disabling SELinux.
5.1 Patch Boot
Download the full firmware package corresponding to the Android device, after unpacking the Boot partition, you can find the layout as follows
header # kernel runtime parameters & other information
kernel # Linux kernel
ramdisk.cpio # boot partition
header
The structure is as follows, wherecmdline
will be passed to the kernel as boot parameters, therefore we can modifycmdline
in the manner, the command to disable SELinux is passed inenforcing=0 androidboot.selinux=permissive
.
cmdline=
os_version=12.0.0
os_patch_level=2021-12
However, in high-version Android systems, many manufacturers no longer parsecmdline
with poor versatility.
5.2 Patch Init
init
is the first user-space process run after the Linux Kernel starts, its main function is to complete initialization, parsing and executioninit.rc
The various services defined, the process is mainly divided into four steps:
FirstStateMain
->SetupSelinux
->SecondStageMain
->ueventd_main
Among themSetupSelinux
The key functions at this stage are as follows:
LoadSelinuxPolicy
:Loading sepolicy strategyselinux_android_restorecon
:Reloading sepolicy strategySelinuxSetEnforcement
:Set SElinux switch
It is obviously crucial thatSelinuxSetEnforcement
The function, whose internal implementation is as follows.
void SelinuxSetEnforcement() {
bool kernel_enforcing = (security_getenforce() == 1);
bool is_enforcing = IsEnforcing();
if (kernel_enforcing != is_enforcing) {
if (security_setenforce(is_enforcing)) {
PLOG(FATAL) << "security_setenforce(" << (is_enforcing ? "true" : "false")
<< ") failed";
}
}
if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result.ok()) {
LOG(FATAL) << "Unable to write to /sys/fs/selinux/checkreqprot: " << result.error();
}
}
bool IsEnforcing() {
if (ALLOW_PERMISSIVE_SELINUX) {
return StatusFromProperty() == SELINUX_ENFORCING;
}
return true;
}
Here only Patch is neededIsEnforcing
so that it always returnsFalse
you can disable it ininit stage
Disable Selinux
5.3 Re-compile Kernel
based onGPL
protocol, the manufacturer will open source the modifiedLinux Kernel
, so it can be disabled by recompiling the kernel during compilation.
The specific method is to set it in the kernel configuration file .configCONFIG_SECURITY_SELINUX=n
.
5.4 Patch Kernel
If the manufacturer does not open source the kernel or the open source is not thorough and cannot be compiled normally, it can also bypass SELinux through the patch method
Here we takefile open operation open
for example, to sort out the related call chain of SELinux
Image source: https://blog.csdn.net/bruk_spp/article/details/107283935
When the user space callsopen
When opening a file, a system call is triggereddo_dentry_open
, then call the Linux LSM public interfacesecurity_file_open
, after which it will go to the SELinux function for handling open operationsselinux_file_open
, the next step SELinux will callavc public function
to implement permission checking and log auditing functions, if an operation exceeds its authority, it will callavc_denied
to prevent this behavior.
Therefore, we only need to patch the relevant logic of preventing operations to disable SElinux.
Summary
In summary, the introduction of SELinux has greatly reduced the losses caused by attacks at the user level, even if root privileges are obtained through vulnerabilities, they will be restricted within a relatively small range of impact. In recent years, with the introduction of numerous hardware and software protection mechanisms, the security of Android has been significantly improved; by using excellent and publicly available security mechanisms to converge the attack surface and enhance the security level, this is also a model for our domestic operating systems to learn from and strive to achieve.
Reference
https://source.android.com/security/selinux
Deep penetration into internal networks using Rustdesk, without going online
Expanding the Android attack surface: Analysis of React Native Android applications
Analysis of Windows spyware, will you still easily download Windows crack software?
JAVA Security | In-depth analysis of the underlying mechanism of Runtime.exec command execution

评论已关闭