允许应用访问特定系统公共路径的一种方法
·
OpenHarmony为了保护应用和用户数据,为每个应用创建了独立的沙箱环境,每个应用能访问的文件路径都是相互隔离的。但是,有些需求可能通过一个供多个应用共享的系统公共目录就非常方便实现。那在OpenHarmony的沙箱保护机制下,也是有办法实现这个需求的。
沙箱配置文件
沙箱路径映射由/etc/sandbox/
路径下的一些json文件配置,每个文件格式如下
{
"common" : [{ // 应用沙盒通用挂载项
"top-sandbox-switch": "ON", // 沙盒总开关 ON: 打开, OFF: 关闭
"app-base" : [{
"sandbox-root" : "/mnt/sandbox/<PackageName>", // 沙盒根路径
"mount-paths" : [{
"src-path" : "/config", // mount的源目录
"sandbox-path" : "/config", // 沙盒挂载路径
"sandbox-flags" : [ "bind", "rec" ], // 挂载方式
"check-action-status": "false" // false 不检查当前项挂载结果, true: 检查当前项挂载结果
}
],
"symbol-links" : [{ // link 的目录项
"target-name" : "/system/bin", // link 的源目录
"link-name" : "/bin", // 链接名称
"check-action-status": "false"
}
]
}],
// 应用独有配置参考
"individual" : [{ // 个别应用单独挂载项
"com.ohos.medialibrary.MediaLibraryDataA" : [{ // 应用名
"sandbox-switch": "ON", // ON: 挂载沙盒路径, OFF: 挂载根路径
"sandbox-root" : "/mnt/sandbox/<PackageName>", // 沙盒根路径
"mount-paths" : [{
"src-path" : "/storage/media/<currentUserId>",
"sandbox-path" : "/storage/media",
"sandbox-flags" : [ "bind", "rec" ],
"check-action-status": "false"
}
],
"symbol-links" : []
}]
}]
}
可以针对特定应用来添加路径映射。
实操
hdc file recv /etc/sandbox/appdata-sandbox.json .
# 编辑appdata-sandbox.json,为com.example.sandboxdemo应用增加独有的映射配置
# 例如,把/data/shared系统公共路径映射到应用的/data/storage/el1/base/shared
hdc shell mount -o rw,remount
hdc file send appdata-sandbox.json /etc/sandbox
# 注意,需要保证源路径存在,否则应用启动失败,可以考虑把创建目录的操作增加到init.cfg配置中
hdc shell mkdir /data/shared
hdc shell reboot
添加的应用独有映射配置如下
{
...
"individual": [
{
"com.example.sandboxdemo": [
{
"sandbox-switch": "ON",
"mount-paths": [
{
"src-path": "/data/shared",
"sandbox-path": "/data/storage/el1/base/shared",
"sandbox-flags": [
"bind",
"rec"
],
"check-action-status": "true"
}
],
"symbol-links": []
}
],
...
}
]
...
}
启动应用后,可以通过hdc shell进入沙箱路径查看映射结果
hdc shell // 进入shell
ps -ef|grep [hapName] // 通过ps命令找到对应应用的pid
nsenter -t [hapPid] -m /bin/sh // 通过上一步找到的应用pid进入对应应用的沙箱环境中
内置到系统镜像
运行时的沙箱配置文件源代码路径在base/startup/appspawn/
下,32位系统使用的是appdata-sandbox.json,64位系统使用的是appdata-sandbox64.json。
如果需要默认为特定应用映射路径,可以直接修改对应的源代码文件,重新构建镜像。
注意事项
需要保证映射的源路径是已经存在的,否则应用启动失败,可以考虑把创建目录的操作增加到init.cfg配置中。
测试时关闭了selinux,不排除需要增加必要selinux策略的可能。
只在OpenHarmony 4.1.1 Release版本上做了验证。
参考资料
更多推荐
所有评论(0)