1. 程式人生 > >android在hal下 如何獲得對一個核心節點的訪問許可權

android在hal下 如何獲得對一個核心節點的訪問許可權

Android 5.0以上,我們發現jni通過hal層去操作核心節點時PERMISSION DENIED 即使在Android原始碼工程目錄下,進入到system/core/rootdir目錄,裡面有一個名為ueventd.rc檔案,往裡面新增一行:/dev/hello 0666 root root ,此操作仍然不能讓上層去讀寫相應的節點, 因為5.0以上採取了SEAndroid/SElinux的安全機制,即使擁有root許可權,或者對某核心節點設定為777的許可權,仍然無法在JNI層訪問。
解決辦法:
1.找到需要訪問該核心節點的程序(process)我的是以system_server程序來訪問
2.開啟檔案AndroidL/android/external/sepolicy/file_contexts.be
新增

/dev/hello    u:object_r:hello_device:s0 

3.開啟檔案AndroidL/android/external/sepolicy/device.te
將剛剛第二步寫的hello_device宣告為dev_type:

type hello_device, dev_type;  

4.AndroidL/android/external/sepolicy/目錄下很多.te檔案都是以程序名來結尾的,比如有針對surfaceflinger程序的surfaceflinger,有針對vold程序的vold.te,
我們是由system_server程序來訪問這個節點的,所以,我們找到system_server.te開啟,加入允許這個程序對/dev/hello的讀寫許可權。

# chr_file表示字元裝置檔案,如果是普通檔案用file,目錄請用dir  
# rw_file_perms代表讀寫許可權  
allow system_server hello_device:chr_file rw_file_perms;  // 允許system_server程序擁有對hello_device的這個字元裝置的讀寫許可權;

這樣system_server中的helloservice就可以順利訪問kernel的節點了,

另外5.1 後在frameworks/base/services/java/com/android/server/SystemServer中add自定義的Service時會報SecurityException,同樣我們需要在external/sepolicy/service_contexts檔案裡面做相應的配置
假設我們addservice的別名叫”hello”
那麼service_contexts就寫成

hello     u:object_r:hello_service:s0

在\external\sepolicy\service.te中新增如下:

type hello_service, system_api_service, system_server_service, service_manager_type;