fix(android): 安全修复 — SHA256原生层计算+TOCTOU+域名白名单

- PackageInstallerModule: DigestInputStream边写边算SHA256, 原生层校验消除TOCTOU
- updater: remove expo-crypto, add download domain whitelist, 错误消息去敏感路径
- package.json: 移除expo-crypto依赖(不再需要JS侧SHA256)
This commit is contained in:
LukeMackin
2026-07-19 01:51:40 +08:00
parent 3e7c98a099
commit 8a747d610a
3 changed files with 38 additions and 33 deletions

View File

@@ -9,24 +9,25 @@ import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition import expo.modules.kotlin.modules.ModuleDefinition
import java.io.File import java.io.File
import java.io.FileInputStream import java.io.FileInputStream
import java.security.DigestInputStream
import java.security.MessageDigest
class PackageInstallerModule : Module() { class PackageInstallerModule : Module() {
override fun definition() = ModuleDefinition { override fun definition() = ModuleDefinition {
Name("PackageInstallerModule") Name("PackageInstallerModule")
AsyncFunction("installApk") { filePath: String -> AsyncFunction("installApk") { filePath: String, expectedSha256: String ->
installApk(filePath) installApk(filePath, expectedSha256)
} }
} }
private fun installApk(filePath: String) { private fun installApk(filePath: String, expectedSha256: String) {
val context: Context = appContext.reactContext ?: return val context: Context = appContext.reactContext ?: return
val apkFile = File(filePath) val apkFile = File(filePath)
if (!apkFile.exists()) throw Exception("APK file not found: $filePath") if (!apkFile.exists()) throw Exception("安装包不存在")
// 检查 REQUEST_INSTALL_PACKAGES 权限
if (!context.packageManager.canRequestPackageInstalls()) { if (!context.packageManager.canRequestPackageInstalls()) {
throw SecurityException("REQUEST_INSTALL_PACKAGES 权限未授予,请在系统设置中允许") throw SecurityException("REQUEST_INSTALL_PACKAGES 权限未授予")
} }
val packageInstaller = context.packageManager.packageInstaller val packageInstaller = context.packageManager.packageInstaller
@@ -38,14 +39,21 @@ class PackageInstallerModule : Module() {
val session = packageInstaller.openSession(sessionId) val session = packageInstaller.openSession(sessionId)
try { try {
// 边写入边计算 SHA256原子化避免 TOCTOU
val sha256 = MessageDigest.getInstance("SHA-256")
FileInputStream(apkFile).use { input -> FileInputStream(apkFile).use { input ->
val digestStream = DigestInputStream(input, sha256)
session.openWrite("package", 0, apkFile.length()).use { output -> session.openWrite("package", 0, apkFile.length()).use { output ->
input.copyTo(output) digestStream.copyTo(output)
session.fsync(output) session.fsync(output)
} }
} }
// 安装完成后发送通知,用户点击即重启 val actualSha256 = sha256.digest().joinToString("") { "%02x".format(it) }
if (actualSha256 != expectedSha256) {
throw SecurityException("SHA256校验失败")
}
val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName) val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)
?: throw Exception("无法获取启动Intent") ?: throw Exception("无法获取启动Intent")
val pendingIntent = PendingIntent.getActivity( val pendingIntent = PendingIntent.getActivity(

View File

@@ -14,7 +14,6 @@
"@yuzu-gca/shared": "workspace:*", "@yuzu-gca/shared": "workspace:*",
"expo": "~52.0.0", "expo": "~52.0.0",
"expo-constants": "~17.0.0", "expo-constants": "~17.0.0",
"expo-crypto": "~14.0.0",
"expo-file-system": "~18.0.0", "expo-file-system": "~18.0.0",
"expo-status-bar": "~2.0.0", "expo-status-bar": "~2.0.0",
"expo-updates": "~26.0.0", "expo-updates": "~26.0.0",

View File

@@ -1,6 +1,5 @@
import { parseVersion, checkUpdate } from '@yuzu-gca/shared'; import { parseVersion, checkUpdate } from '@yuzu-gca/shared';
import Constants from 'expo-constants'; import Constants from 'expo-constants';
import * as Crypto from 'expo-crypto';
import * as FileSystem from 'expo-file-system'; import * as FileSystem from 'expo-file-system';
import { NativeModules, Platform } from 'react-native'; import { NativeModules, Platform } from 'react-native';
@@ -36,28 +35,35 @@ export async function checkJsBundleUpdate(): Promise<{
return { hasUpdate: false, remoteVersion: localVersion }; return { hasUpdate: false, remoteVersion: localVersion };
} }
return { return { hasUpdate: true, remoteVersion: result.remoteVersion.raw };
hasUpdate: true,
remoteVersion: result.remoteVersion.raw,
};
} }
// ============================================================ // ============================================================
// 3. APK 静默安装(大更新) // 3. APK 静默安装(大更新)
// ============================================================ // ============================================================
const ALLOWED_DOWNLOAD_HOSTS = [
'git.childish-ghost.com',
'github.com',
];
const { PackageInstallerModule } = NativeModules; const { PackageInstallerModule } = NativeModules;
/** 计算文件 SHA256 */ function validateUrl(url: string): void {
async function sha256File(fileUri: string): Promise<string> { try {
const base64 = await Crypto.digestStringAsync( const host = new URL(url).hostname;
Crypto.CryptoDigestAlgorithm.SHA256, if (!ALLOWED_DOWNLOAD_HOSTS.some(h => host === h || host.endsWith('.' + h))) {
await FileSystem.readAsStringAsync(fileUri, { encoding: FileSystem.EncodingType.Base64 }), throw new Error(`不允许的下载域名: ${host}`);
); }
return base64; } catch (e) {
if (e instanceof TypeError) throw new Error('下载URL格式无效');
throw e;
}
} }
export async function downloadAndInstallApk(apkUrl: string, expectedSha256: string): Promise<void> { export async function downloadAndInstallApk(apkUrl: string, sha256: string): Promise<void> {
validateUrl(apkUrl);
const localPath = `${FileSystem.cacheDirectory ?? ''}gca-update.apk`; const localPath = `${FileSystem.cacheDirectory ?? ''}gca-update.apk`;
const download = FileSystem.createDownloadResumable( const download = FileSystem.createDownloadResumable(
@@ -73,17 +79,10 @@ export async function downloadAndInstallApk(apkUrl: string, expectedSha256: stri
const result = await download.downloadAsync(); const result = await download.downloadAsync();
if (!result?.uri) throw new Error('APK 下载失败'); if (!result?.uri) throw new Error('APK 下载失败');
// SHA256 完整性校验
const actualSha256 = await sha256File(result.uri);
if (actualSha256 !== expectedSha256) {
throw new Error(`SHA256 校验失败: 期望 ${expectedSha256}, 实际 ${actualSha256}`);
}
console.log(`[OTA] 下载完成, SHA256 校验通过: ${result.uri}`);
if (Platform.OS === 'android' && PackageInstallerModule) { if (Platform.OS === 'android' && PackageInstallerModule) {
await PackageInstallerModule.installApk(result.uri); // SHA256 校验在原生层完成(避免 TOCTOU + 密码学误用)
console.log('[OTA] APK 已提交安装,用户下次重启生效'); await PackageInstallerModule.installApk(result.uri, sha256);
console.log('[OTA] SHA256校验通过APK已提交安装');
} else { } else {
throw new Error('PackageInstaller 原生模块不可用'); throw new Error('PackageInstaller 原生模块不可用');
} }
@@ -111,6 +110,5 @@ export async function onAppStartCheckUpdate(): Promise<{
return { jsUpdate: false, apkUpdate: true }; return { jsUpdate: false, apkUpdate: true };
} }
// type === 'js': expo-updates 自动处理
return { jsUpdate: true, apkUpdate: false }; return { jsUpdate: true, apkUpdate: false };
} }