一、SELinux
SELinux是一种安全系统,Android将SELinux纳入到安卓系统中,用于增加安卓系统的安全性,是安卓的一种访问控制策略。
在SELinux的强力保护下,安卓可以更好的对应用程序数据和系统日志进行访问控制。这不仅减轻了恶意程序对系统的影响力,而且保护了用户不受移动设备上隐藏的恶意代码所攻击。
对于开发者来说,SELinux限制了一些访问权限,导致开发过程进行经常遇到一些权限问题。
1、获取SELinux状态
adb shell getenforce
输出:Enforcing或者Permissive
Enforcing表示SELinux防火墙处于打开状态,访问权限禁止;
Permissive表示SELinux防火墙处于关闭状态,访问权限允许,但是访问权限Log打印正常输入。
提示没有权限的打印Log:
avc: denied { map } for pid=4390 comm="m.adan.rearview" path="/dev/event-log-tags" dev="tmpfs" ino=16386 scontext=u:r:untrusted_app:s0:c77,c256,c512,c768 tcontext=u:
avc: denied { map } for pid=4390 comm="m.adan.rearview" path="/dev/event-log-tags" dev="tmpfs" ino=16386 scontext=u:r:untrusted_app:s0:c77,c256,c512,c768 tcontext=u:object_r:runtime_event_log_tags_file:s0 tclass=file permissive=1
(190606_09:34:16.985)[ 2634.018928] type=1404 audit(1559625607.256:5423): enforcing=1 old_enforcing=0 auid=4294967295 ses=4294967295
2、关闭SELinux
adb shell setenforce 0
在adb shell getenforce得到Permissive,表示防火墙已经关掉了,能够获取到访问权限。注意这时:没有权限的提示Log:avc: denied还是会输出。
3、打开SELinux
adb shell setenforce 1
再adb shell getenforce得到Enforcing,表示防火墙已经打开了,访问权限受限。
4、修改设备或者文件 777权限
打开了SELinux后,还需要打开设备的777的权限,以打开串口为例:
二、安全性
安卓引用了SELinux防火墙是为了增强系统的安全性。上述方式只是一个临时方案,一般情况下SELinux是不能被关掉的。
根据avc: denied的Log信息,可以看到,更多的是针对来路不明的untrusted_app,和一些可能对设备有害的一些访问;
三、Android P的权限申请
1、串口操作
open(“/dev/ttyLP3”, O_RDWR );
2、串口打开失败提示报错
type=1400 audit(0.0:11076): avc: denied { write } for name="ttyLP3" dev="tmpfs" ino=15279 scontext=u:r:untrusted_app:s0:c81,c256,c512,c768 tcontext=u:object_r:tty_device:s0 tclass=chr_file permissive=0
type=1400 audit(1559626415.040:11060): avc: denied { read } for pid=4567 comm="com.ad.carradio" name="anr" dev="mmcblk0p14" ino=131075 scontext=u:r:untrusted_app:s0:c89,c256,c512,c768 tcontext=u:object_r:anr_data_file:s0 tclass=dir permissive=0
type=1400 audit(1559626416.476:11076): avc: denied { write } for pid=3810 comm="com.ad.carcontrol" name="ttyLP3" dev="tmpfs" ino=15279 scontext=u:r:untrusted_app:s0:c81,c256,c512,c768 tcontext=u:object_r:tty_device:s0 tclass=chr_file permissive=0
以上信息可以看到,程序是untrusted_app,对ttyLP3没有write的访问权限
3、系统中的权限申请
各厂商不同以下路径会不一样:
修改:p9.0.0.0\device\fsl\imx8q\sepolicy\file_contexts\file_contexts
#增加我们需要访问的设备
/dev/ttyLP3 u:object_r:ttyLP3_device:s0
修改:p9.0.0.0\device\fsl\imx8q\sepolicy\device.te
#增加设备ttyLP3_device
type ttyLP3_device, dev_type, mlstrustedobject;
修改:p9.0.0.0\device\fsl\imx8q\sepolicy\untrusted_app_25.te
#给untrusted_app添加ttyLP3的权限
allow untrusted_app ttyLP3_device:chr_file rw_file_perms;
修改:p9.0.0.0\device\fsl\imx8q\sepolicy\priv_app.te
#给priv_app添加ttyLP3的权限
allow priv_app ttyLP3_device:chr_file rw_file_perms;
修改:p9.0.0.0\device\fsl\imx8q\sepolicy\system_app.te
#给system_app 添加ttyLP3的权限
allow system_app tty_device:chr_file { open read write ioctl getattr };
修改后重新编译系统,就能增加对串口的访问权限了。
四、报错:违反neverallow规则
修改上述后会引起SELinux的neverallow规则拨错,还需要修改/system/sepolicy/下面的文件。
详细说明请参考:
《Android P系统编译报错SELinux违反Neverallow》