1. 背景知识
关于Android全盘加密功能的实现可以参考https://source.android.google.cn/security/encryption/full-disk。data分区的加密原理是基于块设备层的dm-crypt,实现是通过在mount data分区时添加forceencrypt fstab属性。
目前android版本的ota升级包都是存放在data分区中,重启后recovery会去data分区取升级包后进行升级操作。但是使能forceencrypt后,recovery系统无法正常挂在data分区,按照https://source.android.google.cn/security/encryption/full-disk的原理,data分区会被挂载成tmpfs,那么此时recovery怎么实现升级功能的呢?
2. 解密流程
文中涉及的代码引用自aosp Android7.1。
在installPackage之前processPackage会被调用到,在function的最后rs.uncrypt(filename, progressListener)会被调用到以处理/data目录内的升级包文件。因此,我们看到有一个针对升级文件的解密过程在reboot之前进行,recovery只需要处理解密后的内容即可。
frameworks/base/core/java/android/os/RecoverySystem.java
public static void processPackage(Context context,
File packageFile,
final ProgressListener listener,
final Handler handler)
throws IOException {
...
if (!rs.uncrypt(filename, progressListener)) {
throw new IOException("process package failed");
}
}
uncrypt函数会通过binder调用uncrypt service。
private boolean uncrypt(String packageFile, IRecoverySystemProgressListener listener) {
try {
return mService.uncrypt(packageFile, listener);
} catch (RemoteException unused) {
}
return false;
}
uncrypt service定义在uncrypt.rc中,通过init进程解析启动的。
/system/etc/init/uncrypt.rc
service uncrypt /system/bin/uncrypt
class main
socket uncrypt stream 600 system system
disabled
oneshot
读者有兴趣可以跟进uncrypt.cpp中看下几个调用函数,流程是
main --> uncrypt_wrapper --> uncrpt --> produce_block_map
此处直接进入解密的核心函数produce_block_map进行解析,代码实现的功能在注释中有详述。
bootable/recovery/uncrypt/uncrypt.cpp
/*
path, 输入, 如/data/update.zip
map_file, 输出,如/cache/recovery/block.map
blk_dev, 输入,如/dev/block/bootdevice/by-name/userdata
encrypted,输入,是否加密
socket,输入,通信用socket
*/
static int produce_block_map(const char* path, const char* map_file, const char* blk_dev,
bool encrypted, int socket) {
std::string err;
//删除/cache/recovery/block.map, 新建/cache/recovery/block.map.tmp文件
if (!android::base::RemoveFileIfExists(map_file, &err)) {
ALOGE("failed to remove the existing map file %s: %s", map_file, err.c_str());
return kUncryptFileRemoveError;
}
std::string tmp_map_file = std::string(map_file) + ".tmp";
unique_fd mapfd(open(tmp_map_file.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR));
if (!mapfd) {
ALOGE("failed to open %s: %s\n", tmp_map_file.c_str(), strerror(err