修改kernel文件节点权限

此功能在android12上实现。

这里是使用adb shell setenforce 0临时关闭了selinux。还有另一种代码里临时关闭:Android 12关闭Selinux


avc: denied { write } for name="aaa" dev="sysfs" 
scontext=u:r:system_app:s0 tcontext=u:object_r:sysfs:s0 tclass=file permissive=1
 
avc: denied { open } for path="/sys/kernel/aaa"
 dev="sysfs"  scontext=u:r:system_app:s0 tcontext=u:object_r:sysfs:s0 tclass=file permissive=1
 
avc: denied { getattr } for path="/sys/kernel/aaa" 
dev="sysfs" ino=36016 scontext=u:r:system_app:s0 tcontext=u:object_r:sysfs:s0 tclass=file permissive=1

一开始直接这样写:
system_app.te

allow system_app sysfs:file write;
allow system_app sysfs:file open;
allow system_app sysfs:file getattr;

编译报错:

neverallow on line 129 of system/sepolicy/private/coredomain.te (or line 39773 of policy.conf) violated by allow system_app sysfs:file { write open };
libsepol.report_failure: neverallow on line 532 of system/sepolicy/public/app.te (or line 10596 of policy.conf) violated by allow system_app sysfs:file { write };
libsepol.check_assertions: 2 neverallow failures occurred

违反了neverallow。那就重新定义一个type。
custom/sepolicy/custom//non_plat/file.te

type sys_stat_fs, fs_type, sysfs_type;

file_contexts

/sys/kernel/aaa u:object_r:sys_stat_fs:s0

system_app.te

allow system_app sys_stat_fs:file { write open getattr };

这里{ write open getattr } 改成 rw_file_perms 也可以。
这里的rw_file_perms是一个包含所有的读写权限
另外,还有一个问题,kernel里创建的节点属于root组,system组无法访问。

ls -lZ  /sys/kernel/aaa
-rw-rw-r-- 1 root root 

这个可以在init.rc里修改组(执行chown),然后再加selinux权限。

avc: denied { setattr } for name="aaa" dev="sysfs" ino=36016 scontext=u:r:init:s0
 tcontext=u:object_r:sys_stat_fs:s0 tclass=file permissive=0

完整修改点如下:

system/core/rootdir/init.rc

on post-fs
    chmod 0664 /sys/kernel/aaa
    chown 1000 1000 /sys/kernel/aaa

selinux这里是添加的自定义sepolicy编译目录。
BOARD_SEPOLICY_DIRS += custom/sepolicy/custom/non_plat

custom/sepolicy/custom/non_plat/init.te

allow init sys_stat_fs:file setattr;

custom/sepolicy/custom//non_plat/file.te

type sys_stat_fs, fs_type, sysfs_type;

custom/sepolicy/custom/non_plat/file_contexts

/sys/kernel/aaa u:object_r:sys_stat_fs:s0

custom/sepolicy/custom/non_plat/system_app.te

allow system_app sys_stat_fs:file rw_file_perms;

参考链接:
Android 10 应用层如何操作设备节点/sys/devices
Android 12关闭Selinux
文件开放权限
Android SElinux权限添加,NeverAllow,未生效等全解(超详细)
Android 添加 SELinux权限
MTK平台-Android O版本 App 如何获取自定义节点的访问权限-SELinux
Android系统SELinux详解

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容