Android SELinux权限修改

931 阅读2分钟

「这是我参与2022首次更文挑战的第6天,活动详情查看:2022首次更文挑战」。

SELinux的原理大家可以自己百度了解,这里只讲解遇到这类权限问题时如何解决。

案例背景:

有一个项目中,新增了3个LED灯,驱动新建了相关的文件节点,这里只列出其中的两个,其他类似

/sys/class/leds/rear-light/poweron 控制LED开关

/sys/class/leds/rear-light/brightness 控制LED亮度(0~255)

先看下出现问题时的日志:

nny.factorymode: type=1400 audit(0.0:74): avc: denied { write } for name="poweron" dev="sysfs" ino=28953 scontext=u:r:platform_app:s0:c512,c768 tcontext=u:object_r:sysfs:s0 tclass=file permissive=0

nny.factorymode: type=1400 audit(0.0:82): avc: denied { write } for name="brightness" dev="sysfs" ino=29011 scontext=u:r:platform_app:s0:c512,c768 tcontext=u:object_r:sysfs:s0 tclass=file permissive=0

解决过程

1 提取关键字

scontext: platform_app

tcontext: sysfs

tclass: file

denied: write

2 编写规则

(1)使用audit2allow

a. 提取Log

adb shell "cat /proc/kmsg | grepavc" > avc_log.txt

b. audit2allow -i avc_log.txt ,执行后会输出相关规则,比如我的会输出:

allow platform_app sysfs:file write

将上面一行内容放到 platform_app.te文件的末尾(第一步的scontext,文件位置一般在device目录下)

但是这样会有两个问题,一个是权限放大,这样的话所有的sysfs文件都被赋予了write权限,二是这样会导致never allow 报错,编译时会提示。所以不推荐这种方法

(2)根据规则手动修改

a. 新建类型

在device 目录找到对应的file.te文件,新增类型:

type sysfs_leds, sysfs_type, file_type;

这里的type一定要选对,我刚开始照着别的写的是

type sysfs_leds, sysfs_type, fs_type;

结果一直没效果,最后将fs_type换成file_type后可以了

b. 将节点文件和类型对应

在device目录找到对应的file_contexts文件,添加如下内容,由于相关文件很多,所以下面的语句是包含了该目录下的所有文件:

/sys/class/leds(/.*)? u:object_r:sysfs_leds:s0

后来在步骤c调试的时候发现还是有问题,原因是这个目录下的文件夹是一个link文件,还必须修改源文件,后有增加下面的代码:

/sys/devices/soc/7af6000.i2c/i2c-6/6-0040/leds(/.*)? u:object_r:sysfs_leds:s0

c. 在device目录找到对应的platform_app.te文件增加如下:

allow platform_app sysfs_leds:file { getattr open read write };

allow platform_app sysfs_leds:lnk_file { getattr open read write };

allow platform_app sysfs_leds:dir { search };

上面增加的三行是经过反复调试后才加全的,因为问题不会一次都暴露出来,比如刚开始只提示write权限,改好后会提示getattr权限。验证的话只编译boot.img就可以。