From fe9a47349dbda00ef2d664aeed3f4dca9c8d3641 Mon Sep 17 00:00:00 2001 From: wangfenging Date: Thu, 19 Jun 2025 14:20:44 +0800 Subject: [PATCH] Refactoring the sandbox_util class Signed-off-by: wangfenging --- modules/sandbox/BUILD.gn | 25 +- .../{ => modern}/appspawn_mount_template.c | 0 .../sandbox/{ => modern}/appspawn_sandbox.c | 0 .../sandbox/{ => modern}/appspawn_sandbox.h | 0 .../sandbox/{ => modern}/sandbox_adapter.cpp | 0 .../sandbox/{ => modern}/sandbox_adapter.h | 0 modules/sandbox/{ => modern}/sandbox_cfgvar.c | 0 .../sandbox/{ => modern}/sandbox_debug_mode.c | 0 modules/sandbox/{ => modern}/sandbox_expand.c | 0 modules/sandbox/{ => modern}/sandbox_load.c | 0 .../sandbox/{ => modern}/sandbox_manager.c | 0 modules/sandbox/{ => modern}/sandbox_shared.c | 0 modules/sandbox/{ => modern}/sandbox_shared.h | 0 .../normal/appspawn_sandbox_manager.cpp | 161 ++ modules/sandbox/normal/sandbox_common.cpp | 988 +++++++++++ modules/sandbox/normal/sandbox_common.h | 146 ++ modules/sandbox/normal/sandbox_core.cpp | 1449 +++++++++++++++++ modules/sandbox/normal/sandbox_core.h | 128 ++ modules/sandbox/normal/sandbox_def.h | 161 ++ .../{ => normal}/sandbox_shared_mount.cpp | 89 +- .../{ => normal}/sandbox_shared_mount.h | 3 +- modules/sandbox/sandbox_utils.cpp | 6 +- .../unittest/app_spawn_standard_test/BUILD.gn | 42 +- 23 files changed, 3122 insertions(+), 76 deletions(-) rename modules/sandbox/{ => modern}/appspawn_mount_template.c (100%) rename modules/sandbox/{ => modern}/appspawn_sandbox.c (100%) rename modules/sandbox/{ => modern}/appspawn_sandbox.h (100%) rename modules/sandbox/{ => modern}/sandbox_adapter.cpp (100%) rename modules/sandbox/{ => modern}/sandbox_adapter.h (100%) rename modules/sandbox/{ => modern}/sandbox_cfgvar.c (100%) rename modules/sandbox/{ => modern}/sandbox_debug_mode.c (100%) rename modules/sandbox/{ => modern}/sandbox_expand.c (100%) rename modules/sandbox/{ => modern}/sandbox_load.c (100%) rename modules/sandbox/{ => modern}/sandbox_manager.c (100%) rename modules/sandbox/{ => modern}/sandbox_shared.c (100%) rename modules/sandbox/{ => modern}/sandbox_shared.h (100%) create mode 100644 modules/sandbox/normal/appspawn_sandbox_manager.cpp create mode 100644 modules/sandbox/normal/sandbox_common.cpp create mode 100644 modules/sandbox/normal/sandbox_common.h create mode 100644 modules/sandbox/normal/sandbox_core.cpp create mode 100644 modules/sandbox/normal/sandbox_core.h create mode 100644 modules/sandbox/normal/sandbox_def.h rename modules/sandbox/{ => normal}/sandbox_shared_mount.cpp (90%) rename modules/sandbox/{ => normal}/sandbox_shared_mount.h (96%) diff --git a/modules/sandbox/BUILD.gn b/modules/sandbox/BUILD.gn index 5464f7a9..55e0feff 100644 --- a/modules/sandbox/BUILD.gn +++ b/modules/sandbox/BUILD.gn @@ -17,17 +17,17 @@ import("//build/ohos.gni") if (defined(appspawn_sandbox_new) && appspawn_sandbox_new) { ohos_shared_library("appspawn_sandbox") { sources = [ - "appspawn_mount_template.c", + "modern/appspawn_mount_template.c", + "modern/appspawn_sandbox.c", + "modern/sandbox_adapter.cpp", + "modern/sandbox_cfgvar.c", + "modern/sandbox_debug_mode.c", + "modern/sandbox_expand.c", + "modern/sandbox_load.c", + "modern/sandbox_manager.c", + "modern/sandbox_shared.c", "appspawn_permission.c", - "appspawn_sandbox.c", - "sandbox_adapter.cpp", - "sandbox_cfgvar.c", - "sandbox_debug_mode.c", "sandbox_dec.c", - "sandbox_expand.c", - "sandbox_load.c", - "sandbox_manager.c", - "sandbox_shared.c", ] include_dirs = [ @@ -82,12 +82,15 @@ if (defined(appspawn_sandbox_new) && appspawn_sandbox_new) { "${appspawn_innerkits_path}/permission/appspawn_mount_permission.c", "appspawn_permission.c", "sandbox_dec.c", - "sandbox_shared_mount.cpp", - "sandbox_utils.cpp", + "normal/sandbox_shared_mount.cpp", + "normal/appspawn_sandbox_manager.cpp", + "normal/sandbox_common.cpp", + "normal/sandbox_core.cpp" ] include_dirs = [ ".", + "./normal", "${appspawn_path}/common", "${appspawn_path}/standard", "${appspawn_innerkits_path}/client", diff --git a/modules/sandbox/appspawn_mount_template.c b/modules/sandbox/modern/appspawn_mount_template.c similarity index 100% rename from modules/sandbox/appspawn_mount_template.c rename to modules/sandbox/modern/appspawn_mount_template.c diff --git a/modules/sandbox/appspawn_sandbox.c b/modules/sandbox/modern/appspawn_sandbox.c similarity index 100% rename from modules/sandbox/appspawn_sandbox.c rename to modules/sandbox/modern/appspawn_sandbox.c diff --git a/modules/sandbox/appspawn_sandbox.h b/modules/sandbox/modern/appspawn_sandbox.h similarity index 100% rename from modules/sandbox/appspawn_sandbox.h rename to modules/sandbox/modern/appspawn_sandbox.h diff --git a/modules/sandbox/sandbox_adapter.cpp b/modules/sandbox/modern/sandbox_adapter.cpp similarity index 100% rename from modules/sandbox/sandbox_adapter.cpp rename to modules/sandbox/modern/sandbox_adapter.cpp diff --git a/modules/sandbox/sandbox_adapter.h b/modules/sandbox/modern/sandbox_adapter.h similarity index 100% rename from modules/sandbox/sandbox_adapter.h rename to modules/sandbox/modern/sandbox_adapter.h diff --git a/modules/sandbox/sandbox_cfgvar.c b/modules/sandbox/modern/sandbox_cfgvar.c similarity index 100% rename from modules/sandbox/sandbox_cfgvar.c rename to modules/sandbox/modern/sandbox_cfgvar.c diff --git a/modules/sandbox/sandbox_debug_mode.c b/modules/sandbox/modern/sandbox_debug_mode.c similarity index 100% rename from modules/sandbox/sandbox_debug_mode.c rename to modules/sandbox/modern/sandbox_debug_mode.c diff --git a/modules/sandbox/sandbox_expand.c b/modules/sandbox/modern/sandbox_expand.c similarity index 100% rename from modules/sandbox/sandbox_expand.c rename to modules/sandbox/modern/sandbox_expand.c diff --git a/modules/sandbox/sandbox_load.c b/modules/sandbox/modern/sandbox_load.c similarity index 100% rename from modules/sandbox/sandbox_load.c rename to modules/sandbox/modern/sandbox_load.c diff --git a/modules/sandbox/sandbox_manager.c b/modules/sandbox/modern/sandbox_manager.c similarity index 100% rename from modules/sandbox/sandbox_manager.c rename to modules/sandbox/modern/sandbox_manager.c diff --git a/modules/sandbox/sandbox_shared.c b/modules/sandbox/modern/sandbox_shared.c similarity index 100% rename from modules/sandbox/sandbox_shared.c rename to modules/sandbox/modern/sandbox_shared.c diff --git a/modules/sandbox/sandbox_shared.h b/modules/sandbox/modern/sandbox_shared.h similarity index 100% rename from modules/sandbox/sandbox_shared.h rename to modules/sandbox/modern/sandbox_shared.h diff --git a/modules/sandbox/normal/appspawn_sandbox_manager.cpp b/modules/sandbox/normal/appspawn_sandbox_manager.cpp new file mode 100644 index 00000000..db71f08f --- /dev/null +++ b/modules/sandbox/normal/appspawn_sandbox_manager.cpp @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "securec.h" +#include "appspawn_hook.h" +#include "appspawn_manager.h" +#include "appspawn_utils.h" +#include "sandbox_core.h" + +#define USER_ID_SIZE 16 +#define DIR_MODE 0711 + +int32_t SetAppSandboxProperty(AppSpawnMgr *content, AppSpawningCtx *property) +{ + APPSPAWN_CHECK(property != nullptr, return -1, "Invalid appspwn client"); + APPSPAWN_CHECK(content != nullptr, return -1, "Invalid appspwn content"); + // clear g_mountInfo in the child process + std::map* mapPtr = static_cast*>(GetEl1BundleMountCount()); + if (mapPtr == nullptr) { + APPSPAWN_LOGE("Get el1 bundle mount count failed"); + return APPSPAWN_ARG_INVALID; + } + mapPtr->clear(); + int ret = 0; + // no sandbox + if (CheckAppMsgFlagsSet(property, APP_FLAGS_NO_SANDBOX)) { + return 0; + } + if ((content->content.sandboxNsFlags & CLONE_NEWPID) == CLONE_NEWPID) { + ret = getprocpid(); + if (ret < 0) { + return ret; + } + } + uint32_t sandboxNsFlags = CLONE_NEWNS; + + if (OHOS::AppSpawn::SandboxCore::NeedNetworkIsolated(property)) { + sandboxNsFlags |= content->content.sandboxNsFlags & CLONE_NEWNET ? CLONE_NEWNET : 0; + } + + APPSPAWN_LOGV("SetAppSandboxProperty sandboxNsFlags 0x%{public}x", sandboxNsFlags); + + if (IsNWebSpawnMode(content)) { + ret = OHOS::AppSpawn::SandboxCore::SetAppSandboxPropertyNweb(property, sandboxNsFlags); + } else { + ret = OHOS::AppSpawn::SandboxCore::SetAppSandboxProperty(property, sandboxNsFlags); + } + // for module test do not create sandbox, use APP_FLAGS_IGNORE_SANDBOX to ignore sandbox result + if (CheckAppMsgFlagsSet(property, APP_FLAGS_IGNORE_SANDBOX)) { + APPSPAWN_LOGW("Do not care sandbox result %{public}d", ret); + return 0; + } + return ret; +} + +static int SpawnMountDirToShared(AppSpawnMgr *content, AppSpawningCtx *property) +{ +#ifndef APPSPAWN_SANDBOX_NEW + if (!IsNWebSpawnMode(content)) { + // mount dynamic directory + MountToShared(content, property); + } +#endif + return 0; +} + +static int UninstallDebugSandbox(AppSpawnMgr *content, AppSpawningCtx *property) +{ + APPSPAWN_CHECK(property != nullptr && content != nullptr, return -1, + "Invalid appspawn client or property"); + return OHOS::AppSpawn::SandboxCore::UninstallDebugSandbox(content, property); +} + +static int InstallDebugSandbox(AppSpawnMgr *content, AppSpawningCtx *property) +{ + APPSPAWN_CHECK(property != nullptr && content != nullptr, return -1, + "Invalid appspawn client or property"); + return OHOS::AppSpawn::SandboxCore::InstallDebugSandbox(content, property); +} + +static void UmountDir(const char *rootPath, const char *targetPath, const AppSpawnedProcessInfo *appInfo) +{ + size_t allPathSize = strlen(rootPath) + USER_ID_SIZE + strlen(appInfo->name) + strlen(targetPath) + 2; + char *path = reinterpret_cast(malloc(sizeof(char) * (allPathSize))); + APPSPAWN_CHECK(path != nullptr, return, "Failed to malloc path"); + + int ret = sprintf_s(path, allPathSize, "%s%u/%s%s", rootPath, appInfo->uid / UID_BASE, + appInfo->name, targetPath); + APPSPAWN_CHECK(ret > 0 && ((size_t)ret < allPathSize), free(path); + return, "Failed to get sandbox path errno %{public}d", errno); + + ret = umount2(path, MNT_DETACH); + if (ret == 0) { + APPSPAWN_LOGI("Umount2 sandbox path %{public}s success", path); + } else { + APPSPAWN_LOGW("Failed to umount2 sandbox path %{public}s errno %{public}d", path, errno); + } + free(path); +} + +static int UmountSandboxPath(const AppSpawnMgr *content, const AppSpawnedProcessInfo *appInfo) +{ + APPSPAWN_CHECK(content != nullptr && appInfo != nullptr && appInfo->name != NULL, + return -1, "Invalid content or appInfo"); + if (!IsAppSpawnMode(content)) { + return 0; + } + APPSPAWN_LOGV("UmountSandboxPath name %{public}s pid %{public}d", appInfo->name, appInfo->pid); + const char rootPath[] = "/mnt/sandbox/"; + const char el1Path[] = "/data/storage/el1/bundle"; + + std::string varBundleName = std::string(appInfo->name); + if (appInfo->appIndex > 0) { + varBundleName = "+clone-" + std::to_string(appInfo->appIndex) + "+" + varBundleName; + } + + uint32_t userId = appInfo->uid / UID_BASE; + std::string key = std::to_string(userId) + "-" + varBundleName; + std::map *el1BundleCountMap = static_cast*>(GetEl1BundleMountCount()); + if (el1BundleCountMap == nullptr || el1BundleCountMap->find(key) == el1BundleCountMap->end()) { + return 0; + } + (*el1BundleCountMap)[key]--; + if ((*el1BundleCountMap)[key] == 0) { + APPSPAWN_LOGV("no app %{public}s use it in userId %{public}u, need umount", appInfo->name, userId); + UmountDir(rootPath, el1Path, appInfo); + el1BundleCountMap->erase(key); + } else { + APPSPAWN_LOGV("app %{public}s use it mount times %{public}d in userId %{public}u, not need umount", + appInfo->name, (*el1BundleCountMap)[key], userId); + } + return 0; +} + +#ifndef APPSPAWN_SANDBOX_NEW +MODULE_CONSTRUCTOR(void) +{ + APPSPAWN_LOGV("Load sandbox module ..."); + (void)AddServerStageHook(STAGE_SERVER_PRELOAD, HOOK_PRIO_SANDBOX, + OHOS::AppSpawn::SandboxCommon::LoadAppSandboxConfigCJson); + (void)AddAppSpawnHook(STAGE_PARENT_PRE_FORK, HOOK_PRIO_COMMON, SpawnMountDirToShared); + (void)AddAppSpawnHook(STAGE_CHILD_EXECUTE, HOOK_PRIO_SANDBOX, SetAppSandboxProperty); + (void)AddAppSpawnHook(STAGE_PARENT_UNINSTALL, HOOK_PRIO_SANDBOX, UninstallDebugSandbox); + (void)AddAppSpawnHook(STAGE_PARENT_PRE_FORK, HOOK_PRIO_SANDBOX, InstallDebugSandbox); + (void)AddProcessMgrHook(STAGE_SERVER_APP_UMOUNT, HOOK_PRIO_SANDBOX, UmountSandboxPath); + (void)AddServerStageHook(STAGE_SERVER_EXIT, HOOK_PRIO_SANDBOX, + OHOS::AppSpawn::SandboxCommon::FreeAppSandboxConfigCJson); +} +#endif \ No newline at end of file diff --git a/modules/sandbox/normal/sandbox_common.cpp b/modules/sandbox/normal/sandbox_common.cpp new file mode 100644 index 00000000..b0cb4090 --- /dev/null +++ b/modules/sandbox/normal/sandbox_common.cpp @@ -0,0 +1,988 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sandbox_common.h" + +#include +#include +#include +#include +#include +#include +#include "appspawn_manager.h" +#include "appspawn_utils.h" +#include "sandbox_def.h" +#include "parameters.h" +#include "init_param.h" +#include "init_utils.h" +#include "parameter.h" +#include "config_policy_utils.h" + +#ifdef WITH_SELINUX +#include "hap_restorecon.h" +#ifdef APPSPAWN_MOUNT_TMPSHM +#include "policycoreutils.h" +#endif // APPSPAWN_MOUNT_TMPSHM +#endif // WITH_SELINUX + +namespace OHOS { +namespace AppSpawn { + +int32_t SandboxCommon::deviceTypeEnable_ = -1; +std::map> appSandboxCJsonConfig_ = {}; + +// 加载配置文件 +uint32_t SandboxCommon::GetSandboxNsFlags(bool isNweb) +{ + uint32_t nsFlags = 0; + if (!IsTotalSandboxEnabled(nullptr)) { + return nsFlags; + } + + const std::map NamespaceFlagsMap = { {"pid", CLONE_NEWPID}, + {"net", CLONE_NEWNET} }; + const char *prefixStr = + isNweb ? SandboxCommonDef::g_privatePrefix : SandboxCommonDef::g_commonPrefix; + const char *baseStr = isNweb ? SandboxCommonDef::g_ohosRender.c_str() : SandboxCommonDef::g_appBase; + + auto processor = [&baseStr, &NamespaceFlagsMap, &nsFlags](cJSON *item) { + cJSON *internal = cJSON_GetObjectItemCaseSensitive(item, baseStr); + if (!internal || !cJSON_IsArray(internal)) { + return 0; + } + + // 获取数组中第一个元素 + cJSON *firstElem = cJSON_GetArrayItem(internal, 0); + if (!firstElem) { + return 0; + } + + // 获取 "sandbox-ns-flags" 数组 + cJSON *nsFlagsJson = cJSON_GetObjectItemCaseSensitive(firstElem, SandboxCommonDef::g_sandBoxNsFlags); + if (!nsFlagsJson || !cJSON_IsArray(nsFlagsJson)) { + return 0; + } + cJSON *nsIte = nullptr; + cJSON_ArrayForEach(nsIte, nsFlagsJson) { + const char *sandboxNs = cJSON_GetStringValue(nsIte); + if (sandboxNs == nullptr) { + continue; + } + std::string sandboxNsStr = sandboxNs; + if (!NamespaceFlagsMap.count(sandboxNsStr)) { + continue; + } + nsFlags |= NamespaceFlagsMap.at(sandboxNsStr); + } + return 0; + }; + + for (auto& config : GetCJsonConfig(SandboxCommonDef::SANBOX_APP_JSON_CONFIG)) { + // 获取 "individual" 数组 + cJSON *individual = cJSON_GetObjectItemCaseSensitive(config, prefixStr); + if (!individual || !cJSON_IsArray(individual)) { + return nsFlags; + } + (void)HandleArrayForeach(individual, processor); + } + + if (!nsFlags) { + APPSPAWN_LOGE("config is not found %{public}s ns config", isNweb ? "Nweb" : "App"); + } + return nsFlags; +} + +bool SandboxCommon::AppSandboxPidNsIsSupport(void) +{ + char buffer[10] = {0}; + uint32_t buffSize = sizeof(buffer); + + if (SystemGetParameter("const.sandbox.pidns.support", buffer, &buffSize) != 0) { + return true; + } + if (!strcmp(buffer, "false")) { + return false; + } + return true; +} + +void SandboxCommon::StoreCJsonConfig(cJSON *root, SandboxCommonDef::SandboxConfigType type) +{ + appSandboxCJsonConfig_[type].push_back(root); +} + +int32_t SandboxCommon::HandleArrayForeach(cJSON *arrayJson, ArrayItemProcessor processor) +{ + if (!arrayJson || !cJSON_IsArray(arrayJson) || !processor) { + return APPSPAWN_ERROR_UTILS_DECODE_JSON_FAIL; + } + + int ret = 0; + cJSON *item; + cJSON_ArrayForEach(item, arrayJson) { + ret = processor(item); + if (ret != 0) { + return ret; + } + } + return ret; +} + +int SandboxCommon::LoadAppSandboxConfigCJson(AppSpawnMgr *content) +{ + // load sandbox config + cJSON *sandboxCJsonRoot; + CfgFiles *files = GetCfgFiles("etc/sandbox"); + for (int i = 0; (files != nullptr) && (i < MAX_CFG_POLICY_DIRS_CNT); ++i) { + if (files->paths[i] == nullptr) { + continue; + } + std::string path = files->paths[i]; + std::string appPath = path + SandboxCommonDef::APP_JSON_CONFIG; + APPSPAWN_LOGI("LoadAppSandboxConfig %{public}s", appPath.c_str()); + sandboxCJsonRoot = GetJsonObjFromFile(appPath.c_str()); + APPSPAWN_CHECK((sandboxCJsonRoot != nullptr && cJSON_IsObject(sandboxCJsonRoot)), continue, + "Failed to load app data sandbox config %{public}s", appPath.c_str()); + StoreCJsonConfig(sandboxCJsonRoot, SandboxCommonDef::SANBOX_APP_JSON_CONFIG); + + std::string isolatedPath = path + SandboxCommonDef::APP_ISOLATED_JSON_CONFIG; + APPSPAWN_LOGI("LoadAppSandboxConfig %{public}s", isolatedPath.c_str()); + sandboxCJsonRoot = GetJsonObjFromFile(appPath.c_str()); + APPSPAWN_CHECK((sandboxCJsonRoot != nullptr && cJSON_IsObject(sandboxCJsonRoot)), continue, + "Failed to load app data sandbox config %{public}s", appPath.c_str()); + StoreCJsonConfig(sandboxCJsonRoot, SandboxCommonDef::SANBOX_ISOLATED_JSON_CONFIG); + } + FreeCfgFiles(files); + + bool isNweb = IsNWebSpawnMode(content); + if (!isNweb && !AppSandboxPidNsIsSupport()) { + return 0; + } + content->content.sandboxNsFlags = GetSandboxNsFlags(isNweb); + return 0; +} + +int SandboxCommon::FreeAppSandboxConfigCJson(AppSpawnMgr *content) +{ + UNUSED(content); + std::vector normalJsonVec = GetCJsonConfig(SandboxCommonDef::SANBOX_APP_JSON_CONFIG); + for (auto& normal : normalJsonVec) { + cJSON_Delete(normal); + } + + std::vector isolatedJsonVec = GetCJsonConfig(SandboxCommonDef::SANBOX_APP_JSON_CONFIG); + for (auto& isolated : normalJsonVec) { + cJSON_Delete(isolated); + } + return 0; +} + +std::vector &SandboxCommon::GetCJsonConfig(SandboxCommonDef::SandboxConfigType type) +{ + return appSandboxCJsonConfig_[type]; +} + +// 获取应用信息 +std::string SandboxCommon::GetExtraInfoByType(const AppSpawningCtx *appProperty, const std::string &type) +{ + uint32_t len = 0; + char *info = reinterpret_cast(GetAppPropertyExt(appProperty, type.c_str(), &len)); + if (info == nullptr) { + return ""; + } + return std::string(info, len); +} + +std::string SandboxCommon::GetSandboxRootPath(const AppSpawningCtx *appProperty, cJSON *config) +{ + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (dacInfo == nullptr) { + return ""; + } + + std::string sandboxRoot = ""; + std::string isolatedFlagText = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? "isolated/" : ""; + AppSpawnMsgBundleInfo *bundleInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + if (bundleInfo == nullptr) { + return ""; + } + std::string tmpBundlePath = bundleInfo->bundleName; + std::ostringstream variablePackageName; + if (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_CLONE_ENABLE)) { + variablePackageName << "+clone-" << bundleInfo->bundleIndex << "+" << bundleInfo->bundleName; + tmpBundlePath = variablePackageName.str(); + } + const std::string variableSandboxRoot = SandboxCommonDef::g_sandBoxRootDir + + std::to_string(dacInfo->uid / UID_BASE) + "/" + isolatedFlagText.c_str() + tmpBundlePath; + + const char *sandboxRootChr = GetStringFromJsonObj(config, SandboxCommonDef::g_sandboxRootPrefix); + if (sandboxRootChr != nullptr) { + sandboxRoot = sandboxRootChr; + if (sandboxRoot == SandboxCommonDef::g_originSandboxPath || + sandboxRoot == SandboxCommonDef::g_sandboxRootPathTemplate) { + sandboxRoot = variableSandboxRoot; + } else { + sandboxRoot = ConvertToRealPath(appProperty, sandboxRoot); + APPSPAWN_LOGV("set sandbox-root name is %{public}s", sandboxRoot.c_str()); + } + } else { + sandboxRoot = variableSandboxRoot; + APPSPAWN_LOGV("set sandbox-root to default rootapp name is %{public}s", GetBundleName(appProperty)); + } + + return sandboxRoot; +} + +int SandboxCommon::CreateDirRecursive(const std::string &path, mode_t mode) +{ + return MakeDirRec(path.c_str(), mode, 1); +} + +void SandboxCommon::CreateDirRecursiveWithClock(const std::string &path, mode_t mode) +{ + size_t size = path.size(); + if (size == 0) { + return; + } +#ifdef APPSPAWN_HISYSEVENT + struct timespec startClock = {0}; + clock_gettime(CLOCK_MONOTONIC, &startClock); +#endif + size_t index = 0; + do { + size_t pathIndex = path.find_first_of('/', index); + index = pathIndex == std::string::npos ? size : pathIndex + 1; + std::string dir = path.substr(0, index); +#ifndef APPSPAWN_TEST + APPSPAWN_CHECK(!(access(dir.c_str(), F_OK) < 0 && mkdir(dir.c_str(), mode) < 0), + return, "errno is %{public}d, mkdir %{public}s failed", errno, dir.c_str()); +#endif + } while (index < size); + +#ifdef APPSPAWN_HISYSEVENT + struct timespec endClock = {0}; + clock_gettime(CLOCK_MONOTONIC, &endClock); + uint64_t diff = DiffTime(&startClock, &endClock); + + APPSPAWN_CHECK_ONLY_EXPER(diff < FUNC_REPORT_DURATION, + ReportAbnormalDuration("MakeDirRecursive", diff)); +#endif +} + +bool SandboxCommon::VerifyDirRecursive(const std::string &path) +{ + size_t size = path.size(); + if (size == 0) { + return false; + } + size_t index = 0; + do { + size_t pathIndex = path.find_first_of('/', index); + index = pathIndex == std::string::npos ? size : pathIndex + 1; + std::string dir = path.substr(0, index); +#ifndef APPSPAWN_TEST + APPSPAWN_CHECK(access(dir.c_str(), F_OK) == 0, + return false, "check dir %{public}s failed, strerror: %{public}s", dir.c_str(), strerror(errno)); +#endif + } while (index < size); + return true; +} + +void SandboxCommon::CreateFileIfNotExist(const char *file) +{ + if (access(file, F_OK) == 0) { + APPSPAWN_LOGI("file %{public}s already exist", file); + return; + } + std::string path = file; + auto pos = path.find_last_of('/'); + APPSPAWN_CHECK(pos != std::string::npos, return, "file %{public}s error", file); + std::string dir = path.substr(0, pos); + (void)CreateDirRecursive(dir, SandboxCommonDef::FILE_MODE); + int fd = open(file, O_CREAT, SandboxCommonDef::FILE_MODE); + if (fd < 0) { + APPSPAWN_LOGW("failed create %{public}s, err=%{public}d", file, errno); + } else { + close(fd); + } + return; +} + +void SandboxCommon::SetSandboxPathChmod(cJSON *jsonConfig, std::string &sandboxRoot) +{ + const std::map modeMap = {{"S_IRUSR", S_IRUSR}, {"S_IWUSR", S_IWUSR}, {"S_IXUSR", S_IXUSR}, + {"S_IRGRP", S_IRGRP}, {"S_IWGRP", S_IWGRP}, {"S_IXGRP", S_IXGRP}, + {"S_IROTH", S_IROTH}, {"S_IWOTH", S_IWOTH}, {"S_IXOTH", S_IXOTH}, + {"S_IRWXU", S_IRWXU}, {"S_IRWXG", S_IRWXG}, {"S_IRWXO", S_IRWXO}}; + const char *fileMode = GetStringFromJsonObj(jsonConfig, SandboxCommonDef::g_destMode); + if (fileMode == nullptr) { + return; + } + + mode_t mode = 0; + std::string fileModeStr = fileMode; + std::vector modeVec = SplitString(fileModeStr, "|"); + for (unsigned int i = 0; i < modeVec.size(); i++) { + if (modeMap.count(modeVec[i])) { + mode |= modeMap.at(modeVec[i]); + } + } + + chmod(sandboxRoot.c_str(), mode); +} + +// 获取挂载配置参数信息 +unsigned long SandboxCommon::GetMountFlagsFromConfig(const std::vector &vec) +{ + const std::map MountFlagsMap = { {"rec", MS_REC}, {"MS_REC", MS_REC}, + {"bind", MS_BIND}, {"MS_BIND", MS_BIND}, + {"move", MS_MOVE}, {"MS_MOVE", MS_MOVE}, + {"slave", MS_SLAVE}, {"MS_SLAVE", MS_SLAVE}, + {"rdonly", MS_RDONLY}, {"MS_RDONLY", MS_RDONLY}, + {"shared", MS_SHARED}, {"MS_SHARED", MS_SHARED}, + {"unbindable", MS_UNBINDABLE}, + {"MS_UNBINDABLE", MS_UNBINDABLE}, + {"remount", MS_REMOUNT}, {"MS_REMOUNT", MS_REMOUNT}, + {"nosuid", MS_NOSUID}, {"MS_NOSUID", MS_NOSUID}, + {"nodev", MS_NODEV}, {"MS_NODEV", MS_NODEV}, + {"noexec", MS_NOEXEC}, {"MS_NOEXEC", MS_NOEXEC}, + {"noatime", MS_NOATIME}, {"MS_NOATIME", MS_NOATIME}, + {"lazytime", MS_LAZYTIME}, {"MS_LAZYTIME", MS_LAZYTIME}}; + + unsigned long mountFlags = 0; + for (unsigned int i = 0; i < vec.size(); i++) { + if (MountFlagsMap.count(vec[i])) { + mountFlags |= MountFlagsMap.at(vec[i]); + } + } + return mountFlags; +} + +bool SandboxCommon::IsDacOverrideEnabled(cJSON *config) // GetSandboxDacOverrideEnable +{ + return GetBoolValueFromJsonObj(config, SandboxCommonDef::g_dacOverrideSensitive, false); +} + +bool SandboxCommon::GetSwitchStatus(cJSON *config) // GetSbxSwitchStatusByConfig +{ + // if not find sandbox-switch node, default switch status is true + return GetBoolValueFromJsonObj(config, SandboxCommonDef::g_sandBoxSwitchPrefix, true); +} + +uint32_t SandboxCommon::ConvertFlagStr(const std::string &flagStr) +{ + const std::map flagsMap = {{"0", 0}, {"START_FLAGS_BACKUP", 1}, + {"DLP_MANAGER", 2}, + {"DEVELOPER_MODE", 17}, + {"PREINSTALLED_HAP", 29}, + {"CUSTOM_SANDBOX_HAP", 31}}; + + if (flagsMap.count(flagStr)) { + return 1 << flagsMap.at(flagStr); + } + return 0; +} + +unsigned long SandboxCommon::GetMountFlags(cJSON *config) // GetSandboxMountFlags +{ + unsigned long mountFlags = SandboxCommonDef::BASIC_MOUNT_FLAGS; + std::vector vec; + cJSON *customizedFlags = IsDacOverrideEnabled(config) ? + cJSON_GetObjectItemCaseSensitive(config, SandboxCommonDef::g_sandBoxFlagsCustomized) : + cJSON_GetObjectItemCaseSensitive(config, SandboxCommonDef::g_sandBoxFlags); + if (customizedFlags == nullptr || !cJSON_IsArray(customizedFlags)) { + return mountFlags; + } + + auto processor = [&vec](cJSON *item) { + const char *strItem = cJSON_GetStringValue(item); + if (strItem == nullptr) { + return -1; + } + vec.emplace_back(strItem); + return 0; + }; + + if (HandleArrayForeach(customizedFlags, processor) != 0) { + return mountFlags; + } + return GetMountFlagsFromConfig(vec); +} + +std::string SandboxCommon::GetFsType(cJSON *config) // GetSandboxFsType +{ + std::string fsType = ""; + const char *fsTypeChr = GetStringFromJsonObj(config, SandboxCommonDef::g_fsType); + if (fsTypeChr == nullptr) { + return fsType; + } + fsType = fsTypeChr; + return fsType; +} + +std::string SandboxCommon::GetOptions(const AppSpawningCtx *appProperty, cJSON *config) // GetSandboxOptions +{ + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (dacInfo == nullptr) { + return ""; + } + + std::string options = ""; + const char *optionsChr = GetStringFromJsonObj(config, SandboxCommonDef::g_sandBoxOptions); + if (optionsChr == nullptr) { + return options; + } + options = optionsChr; + options += ",user_id=" + std::to_string(dacInfo->uid /UID_BASE); + return options; +} + +std::vector SandboxCommon::GetDecPath(const AppSpawningCtx *appProperty, cJSON *config) // GetSandboxDecPath +{ + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (dacInfo == nullptr) { + return {}; + } + + std::vector decPaths = {}; + cJSON *decPathJson = cJSON_GetObjectItemCaseSensitive(config, SandboxCommonDef::g_sandBoxDecPath); + if (decPathJson == nullptr || !cJSON_IsArray(decPathJson)) { + return {}; + } + + auto processor = [&appProperty, &decPaths](cJSON *item) { + const char *strItem = cJSON_GetStringValue(item); + if (strItem == nullptr) { + return -1; + } + std::string decPath = ConvertToRealPath(appProperty, strItem); + decPaths.emplace_back(std::move(decPath)); + return 0; + }; + if (HandleArrayForeach(decPathJson, processor) != 0) { + return {}; + } + return decPaths; +} + +bool SandboxCommon::IsCreateSandboxPathEnabled(cJSON *json, std::string srcPath) // GetCreateSandboxPath +{ + bool isRet = GetBoolValueFromJsonObj(json, SandboxCommonDef::CREATE_SANDBOX_PATH, false); + if (!isRet && access(srcPath.c_str(), F_OK) != 0) { + return false; + } + return true; +} + +bool SandboxCommon::IsTotalSandboxEnabled(const AppSpawningCtx *appProperty) // CheckTotalSandboxSwitchStatus +{ + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANBOX_APP_JSON_CONFIG; + + for (auto& wholeConfig : GetCJsonConfig(type)) { + // 获取 "common" 数组 + cJSON *common = cJSON_GetObjectItemCaseSensitive(wholeConfig, SandboxCommonDef::g_commonPrefix); + if (!common || !cJSON_IsArray(common)) { + continue; + } + // 获取第一个字段 + cJSON *firstCommon = cJSON_GetArrayItem(common, 0); + if (!firstCommon) { + continue; + } + return GetBoolValueFromJsonObj(firstCommon, SandboxCommonDef::g_topSandBoxSwitchPrefix, true); + } + // default sandbox switch is on + return true; +} + +bool SandboxCommon::IsAppSandboxEnabled(const AppSpawningCtx *appProperty) // CheckAppSandboxSwitchStatus +{ + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANBOX_APP_JSON_CONFIG; + + for (auto& wholeConfig : GetCJsonConfig(type)) { + // 获取 "individual" 数组 + cJSON *individual = cJSON_GetObjectItemCaseSensitive(wholeConfig, SandboxCommonDef::g_privatePrefix); + if (!individual || !cJSON_IsArray(individual)) { + continue; + } + cJSON *bundleNameInfo = cJSON_GetObjectItemCaseSensitive(individual, GetBundleName(appProperty)); + if (!bundleNameInfo || !cJSON_IsArray(bundleNameInfo)) { + continue; + } + // 获取第一个字段 + cJSON *firstCommon = cJSON_GetArrayItem(bundleNameInfo, 0); + if (!firstCommon) { + continue; + } + return GetSwitchStatus(firstCommon); + } + // default sandbox switch is on + return true; +} + +void SandboxCommon::GetSandboxMountConfig(const AppSpawningCtx *appProperty, const std::string §ion, + cJSON *mntPoint, SandboxMountConfig &mountConfig) +{ + if (section.compare(SandboxCommonDef::g_permissionPrefix) == 0) { + mountConfig.optionsPoint = GetOptions(appProperty, mntPoint); + mountConfig.fsType = GetFsType(mntPoint); + mountConfig.decPaths = GetDecPath(appProperty, mntPoint); + } else { + mountConfig.fsType = GetFsType(mntPoint); + mountConfig.optionsPoint = ""; + mountConfig.decPaths = {}; + } + return; +} + +// 校验操作 +bool SandboxCommon::IsNeededCheckPathStatus(const AppSpawningCtx *appProperty, const char *path) +{ + if (strstr(path, "data/app/el1/") || strstr(path, "data/app/el2/")) { + return true; + } + if ((strstr(path, "data/app/el3/") || strstr(path, "data/app/el4/") || strstr(path, "data/app/el5/")) && + CheckAppMsgFlagsSet(appProperty, APP_FLAGS_UNLOCKED_STATUS)) { + return true; + } + return false; +} + +void SandboxCommon::CheckMountStatus(const std::string &path) +{ + std::ifstream file("/proc/self/mountinfo"); + if (!file.is_open()) { + APPSPAWN_LOGE("Failed to open /proc/self/mountinfo errno %{public}d", errno); + return; + } + + bool flag = false; + std::string line; + while (std::getline(file, line)) { + if (line.find(path) != std::string::npos) { + flag = true; + APPSPAWN_LOGI("Current mountinfo %{public}s", line.c_str()); + } + } + file.close(); + APPSPAWN_CHECK_ONLY_LOG(flag, "Mountinfo not contains %{public}s", path.c_str()); +} + +bool SandboxCommon::HasPrivateInBundleName(const std::string &bundleName) // CheckBundleNameForPrivate +{ + if (bundleName.find(SandboxCommonDef::g_internal) != std::string::npos) { + return false; + } + return true; +} + +bool SandboxCommon::IsMountSuccessful(cJSON *mntPoint) // GetCheckStatus +{ + // default false + return GetBoolValueFromJsonObj(mntPoint, SandboxCommonDef::g_actionStatuc, false); +} + +int SandboxCommon::CheckBundleName(const std::string &bundleName) +{ + if (bundleName.empty() || bundleName.size() > APP_LEN_BUNDLE_NAME) { + return -1; + } + if (bundleName.find('\\') != std::string::npos || bundleName.find('/') != std::string::npos) { + return -1; + } + return 0; +} + +int32_t SandboxCommon::CheckAppFullMountEnable() +{ + if (deviceTypeEnable_ != -1) { + return deviceTypeEnable_; + } + + char value[] = "false"; + int32_t ret = GetParameter("const.filemanager.full_mount.enable", "false", value, sizeof(value)); + if (ret > 0 && (strcmp(value, "true")) == 0) { + deviceTypeEnable_ = SandboxCommonDef::FILE_CROSS_APP_STATUS; + } else if (ret > 0 && (strcmp(value, "false")) == 0) { + deviceTypeEnable_ = SandboxCommonDef::FILE_ACCESS_COMMON_DIR_STATUS; + } else { + deviceTypeEnable_ = -1; + } + + return deviceTypeEnable_; +} + +bool SandboxCommon::IsPrivateSharedStatus(const std::string &bundleName, AppSpawningCtx *appProperty) +{ + bool result = false; + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANBOX_APP_JSON_CONFIG; + + for (auto& config : GetCJsonConfig(type)) { + // 获取 "individual" 数组 + cJSON *individual = cJSON_GetObjectItemCaseSensitive(config, SandboxCommonDef::g_privatePrefix); + if (!individual || !cJSON_IsArray(individual)) { + return result; + } + cJSON *bundleNameInfo = cJSON_GetObjectItemCaseSensitive(individual, bundleName.c_str()); + if (!bundleNameInfo || !cJSON_IsArray(bundleNameInfo)) { + return result; + } + result = GetBoolValueFromJsonObj(bundleNameInfo, SandboxCommonDef::g_sandBoxShared, false); + } + return result; +} + +bool SandboxCommon::IsValidMountConfig(cJSON *mntPoint, const AppSpawningCtx *appProperty, bool checkFlag) +{ + const char *srcPath = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_srcPath); + const char *sandboxPath = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_sandBoxPath); + cJSON *customizedFlags = cJSON_GetObjectItemCaseSensitive(mntPoint, SandboxCommonDef::g_sandBoxFlagsCustomized); + cJSON *flags = cJSON_GetObjectItemCaseSensitive(mntPoint, SandboxCommonDef::g_sandBoxFlags); + if (srcPath == nullptr || sandboxPath == nullptr || (customizedFlags == nullptr && flags == nullptr)) { + APPSPAWN_LOGE("read mount config failed, app name is %{public}s", GetBundleName(appProperty)); + return false; + } + + AppSpawnMsgDomainInfo *info = + reinterpret_cast(GetAppProperty(appProperty, TLV_DOMAIN_INFO)); + APPSPAWN_CHECK(info != nullptr, return false, "Filed to get domain info %{public}s", GetBundleName(appProperty)); + const char *appAplName = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_appAplName); + if (appAplName != nullptr) { + if (!strcmp(appAplName, info->apl)) { + return false; + } + } + + const std::string configSrcPath = srcPath; + // special handle wps and don't use /data/app/xxx/ config + if (checkFlag && (configSrcPath.find("/data/app") != std::string::npos && + (configSrcPath.find("/base") != std::string::npos || + configSrcPath.find("/database") != std::string::npos + ) && configSrcPath.find(SandboxCommonDef::g_packageName) != std::string::npos)) { + return false; + } + + return true; +} + +// 路径处理 +std::string SandboxCommon::ReplaceAllVariables(std::string str, const std::string& from, const std::string& to) +{ + while (true) { + std::string::size_type pos(0); + if ((pos = str.find(from)) != std::string::npos) { + str.replace(pos, from.length(), to); + } else { + break; + } + } + return str; +} + +std::vector SandboxCommon::SplitString(std::string &str, const std::string &delimiter) +{ + std::string::size_type pos; + std::vector result; + str += delimiter; + size_t size = str.size(); + for (unsigned int i = 0; i < size; i++) { + pos = str.find(delimiter, i); + if (pos < size) { + std::string s = str.substr(i, pos - i); + result.push_back(s); + i = pos + delimiter.size() - 1; + } + } + + return result; +} + +void SandboxCommon::MakeAtomicServiceDir(const AppSpawningCtx *appProperty, std::string path, + std::string variablePackageName) +{ + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + APPSPAWN_CHECK(dacInfo != nullptr, return, "No dac info in msg app property"); + if (path.find("/mnt/share") != std::string::npos) { + path = "/data/service/el2/" + std::to_string(dacInfo->uid / UID_BASE) + "/share/" + variablePackageName; + } + struct stat st = {}; + if (stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) { + return; + } + + int ret = mkdir(path.c_str(), S_IRWXU); + APPSPAWN_CHECK(ret == 0, return, "mkdir %{public}s failed, errno %{public}d", path.c_str(), errno); + + if (path.find("/database") != std::string::npos || path.find("/data/service/el2") != std::string::npos) { + ret = chmod(path.c_str(), S_IRWXU | S_IRWXG | S_ISGID); + } else if (path.find("/log") != std::string::npos) { + ret = chmod(path.c_str(), S_IRWXU | S_IRWXG); + } + APPSPAWN_CHECK(ret == 0, return, "chmod %{public}s failed, errno %{public}d", path.c_str(), errno); + +#ifdef WITH_SELINUX + AppSpawnMsgDomainInfo *msgDomainInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_DOMAIN_INFO)); + APPSPAWN_CHECK(msgDomainInfo != nullptr, return, "No domain info for %{public}s", GetProcessName(appProperty)); + HapContext hapContext; + HapFileInfo hapFileInfo; + hapFileInfo.pathNameOrig.push_back(path); + hapFileInfo.apl = msgDomainInfo->apl; + hapFileInfo.packageName = GetBundleName(appProperty); + hapFileInfo.hapFlags = msgDomainInfo->hapFlags; + if (CheckAppMsgFlagsSet(appProperty, APP_FLAGS_DEBUGGABLE)) { + hapFileInfo.hapFlags |= SELINUX_HAP_DEBUGGABLE; + } + if ((path.find("/base") != std::string::npos) || (path.find("/database") != std::string::npos)) { + ret = hapContext.HapFileRestorecon(hapFileInfo); + APPSPAWN_CHECK(ret == 0, return, "set dir %{public}s selinuxLabel failed, apl %{public}s, ret %{public}d", + path.c_str(), hapFileInfo.apl.c_str(), ret); + } +#endif + if (path.find("/base") != std::string::npos || path.find("/data/service/el2") != std::string::npos) { + ret = chown(path.c_str(), dacInfo->uid, dacInfo->gid); + } else if (path.find("/database") != std::string::npos) { + ret = chown(path.c_str(), dacInfo->uid, DecodeGid("ddms")); + } else if (path.find("/log") != std::string::npos) { + ret = chown(path.c_str(), dacInfo->uid, DecodeGid("log")); + } + APPSPAWN_CHECK(ret == 0, return, "chown %{public}s failed, errno %{public}d", path.c_str(), errno); + return; +} + +std::string SandboxCommon::ReplaceVariablePackageName(const AppSpawningCtx *appProperty, const std::string &path) +{ + std::string tmpSandboxPath = path; + AppSpawnMsgBundleInfo *bundleInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + APPSPAWN_CHECK(bundleInfo != nullptr, return "", "No bundle info in msg %{public}s", GetBundleName(appProperty)); + + char *extension; + uint32_t flags = CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_ATOMIC_SERVICE) ? 0x4 : 0; + if (flags == 0) { + flags = (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_CLONE_ENABLE) && + bundleInfo->bundleIndex > 0) ? 0x1 : 0; + flags |= CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_EXTENSION_SANDBOX) ? 0x2 : 0; + extension = reinterpret_cast( + GetAppSpawnMsgExtInfo(appProperty->message, MSG_EXT_NAME_APP_EXTENSION, nullptr)); + } + std::ostringstream variablePackageName; + switch (flags) { + case SANDBOX_PACKAGENAME_DEFAULT: // 0 default + variablePackageName << bundleInfo->bundleName; + break; + case SANDBOX_PACKAGENAME_CLONE: // 1 +clone-bundleIndex+packageName + variablePackageName << "+clone-" << bundleInfo->bundleIndex << "+" << bundleInfo->bundleName; + break; + case SANDBOX_PACKAGENAME_EXTENSION: { // 2 +extension-+packageName + APPSPAWN_CHECK(extension != nullptr, return "", "Invalid extension data "); + variablePackageName << "+extension-" << extension << "+" << bundleInfo->bundleName; + break; + } + case SANDBOX_PACKAGENAME_CLONE_AND_EXTENSION: { // 3 +clone-bundleIndex+extension-+packageName + APPSPAWN_CHECK(extension != nullptr, return "", "Invalid extension data "); + variablePackageName << "+clone-" << bundleInfo->bundleIndex << "+extension" << "-" << + extension << "+" << bundleInfo->bundleName; + break; + } + case SANDBOX_PACKAGENAME_ATOMIC_SERVICE: { // 4 +auid-+packageName + std::string accountId = GetExtraInfoByType(appProperty, MSG_EXT_NAME_ACCOUNT_ID); + variablePackageName << "+auid-" << accountId << "+" << bundleInfo->bundleName; + std::string atomicServicePath = path; + atomicServicePath = ReplaceAllVariables(atomicServicePath, SandboxCommonDef::g_variablePackageName, + variablePackageName.str()); + MakeAtomicServiceDir(appProperty, atomicServicePath, variablePackageName.str()); + break; + } + default: + variablePackageName << bundleInfo->bundleName; + break; + } + tmpSandboxPath = ReplaceAllVariables(tmpSandboxPath, SandboxCommonDef::g_variablePackageName, variablePackageName.str()); + APPSPAWN_LOGV("tmpSandboxPath %{public}s", tmpSandboxPath.c_str()); + return tmpSandboxPath; +} + +std::string SandboxCommon::ReplaceHostUserId(const AppSpawningCtx *appProperty, const std::string &path) +{ + std::string tmpSandboxPath = path; + int32_t uid = 0; + const char *userId = + (const char *)(GetAppSpawnMsgExtInfo(appProperty->message, MSG_EXT_NAME_PARENT_UID, nullptr)); + if (userId != nullptr) { + uid = atoi(userId); + } + tmpSandboxPath = ReplaceAllVariables(tmpSandboxPath, SandboxCommonDef::g_hostUserId, + std::to_string(uid / UID_BASE)); + APPSPAWN_LOGV("tmpSandboxPath %{public}s", tmpSandboxPath.c_str()); + return tmpSandboxPath; +} + +std::string SandboxCommon::ReplaceClonePackageName(const AppSpawningCtx *appProperty, const std::string &path) +{ + std::string tmpSandboxPath = path; + AppSpawnMsgBundleInfo *bundleInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + APPSPAWN_CHECK(bundleInfo != nullptr, return "", "No bundle info in msg %{public}s", GetBundleName(appProperty)); + + std::string tmpBundlePath = bundleInfo->bundleName; + std::ostringstream variablePackageName; + if (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_CLONE_ENABLE)) { + variablePackageName << "+clone-" << bundleInfo->bundleIndex << "+" << bundleInfo->bundleName; + tmpBundlePath = variablePackageName.str(); + } + + tmpSandboxPath = ReplaceAllVariables(tmpSandboxPath, SandboxCommonDef::g_clonePackageName, tmpBundlePath); + APPSPAWN_LOGV("tmpSandboxPath %{public}s", tmpSandboxPath.c_str()); + return tmpSandboxPath; +} + +const std::string& SandboxCommon::GetArkWebPackageName(void) +{ + static std::string arkWebPackageName; + if (arkWebPackageName.empty()) { + arkWebPackageName = system::GetParameter(SandboxCommonDef::ARK_WEB_PERSIST_PACKAGE_NAME, ""); + } + return arkWebPackageName; +} + +std::string SandboxCommon::ConvertToRealPathWithPermission(const AppSpawningCtx *appProperty, std::string path) +{ + AppSpawnMsgBundleInfo *info = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + if (info == nullptr) { + return ""; + } + if (path.find(SandboxCommonDef::g_packageNameIndex) != std::string::npos) { + std::string bundleNameWithIndex = info->bundleName; + if (info->bundleIndex != 0) { + bundleNameWithIndex = std::to_string(info->bundleIndex) + "_" + bundleNameWithIndex; + } + path = ReplaceAllVariables(path, SandboxCommonDef::g_packageNameIndex, bundleNameWithIndex); + } + + if (path.find(SandboxCommonDef::g_packageName) != std::string::npos) { + path = ReplaceAllVariables(path, SandboxCommonDef::g_packageName, info->bundleName); + } + + if (path.find(SandboxCommonDef::g_userId) != std::string::npos) { + if (deviceTypeEnable_ == SandboxCommonDef::FILE_CROSS_APP_STATUS) { + path = ReplaceAllVariables(path, SandboxCommonDef::g_userId, "currentUser"); + } else if (deviceTypeEnable_ == SandboxCommonDef::FILE_ACCESS_COMMON_DIR_STATUS) { + path = ReplaceAllVariables(path, SandboxCommonDef::g_userId, "currentUser"); + } else { + return ""; + } + } + return path; +} + +std::string SandboxCommon::ConvertToRealPath(const AppSpawningCtx *appProperty, std::string path) +{ + AppSpawnMsgBundleInfo *info = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (info == nullptr || dacInfo == nullptr) { + return ""; + } + if (path.find(SandboxCommonDef::g_packageNameIndex) != std::string::npos) { + std::string bundleNameWithIndex = info->bundleName; + if (info->bundleIndex != 0) { + bundleNameWithIndex = std::to_string(info->bundleIndex) + "_" + bundleNameWithIndex; + } + path = ReplaceAllVariables(path, SandboxCommonDef::g_packageNameIndex, bundleNameWithIndex); + } + + if (path.find(SandboxCommonDef::g_packageName) != std::string::npos) { + path = ReplaceAllVariables(path, SandboxCommonDef::g_packageName, info->bundleName); + } + + if (path.find(SandboxCommonDef::g_userId) != std::string::npos) { + path = ReplaceAllVariables(path, SandboxCommonDef::g_userId, std::to_string(dacInfo->uid / UID_BASE)); + } + + if (path.find(SandboxCommonDef::g_hostUserId) != std::string::npos) { + path = ReplaceHostUserId(appProperty, path); + } + + if (path.find(SandboxCommonDef::g_variablePackageName) != std::string::npos) { + path = ReplaceVariablePackageName(appProperty, path); + } + + if (path.find(SandboxCommonDef::g_clonePackageName) != std::string::npos) { + path = ReplaceClonePackageName(appProperty, path); + } + + if (path.find(SandboxCommonDef::g_arkWebPackageName) != std::string::npos) { + path = ReplaceAllVariables(path, SandboxCommonDef::g_arkWebPackageName, GetArkWebPackageName()); + APPSPAWN_LOGV("arkWeb sandbox, path %{public}s, package:%{public}s", + path.c_str(), GetArkWebPackageName().c_str()); + } + + return path; +} + +// 挂载操作 +int32_t SandboxCommon::DoAppSandboxMountOnce(const AppSpawningCtx *appProperty, const SharedMountArgs *arg) +{ + if (!(arg && arg->srcPath && arg->destPath && arg->srcPath[0] != '\0' && arg->destPath[0] != '\0')) { + return 0; + } + if (strstr(arg->srcPath, "system/etc/hosts") != nullptr || strstr(arg->srcPath, "system/etc/profile") != nullptr) { + CreateFileIfNotExist(arg->destPath); + } else { + (void)CreateDirRecursive(arg->destPath, SandboxCommonDef::FILE_MODE); + } + + int ret = 0; + // to mount fs and bind mount files or directory + struct timespec mountStart = {0}; + clock_gettime(CLOCK_MONOTONIC_COARSE, &mountStart); + APPSPAWN_LOGV("Bind mount %{public}s to %{public}s '%{public}s' '%{public}lu' '%{public}s' '%{public}u'", + arg->srcPath, arg->destPath, arg->fsType, arg->mountFlags, arg->options, arg->mountSharedFlag); + ret = mount(arg->srcPath, arg->destPath, arg->fsType, arg->mountFlags, arg->options); + struct timespec mountEnd = {0}; + clock_gettime(CLOCK_MONOTONIC_COARSE, &mountEnd); + uint64_t diff = DiffTime(&mountStart, &mountEnd); + APPSPAWN_CHECK_ONLY_LOG(diff < SandboxCommonDef::MAX_MOUNT_TIME, "mount %{public}s time %{public}" PRId64 " us", arg->srcPath, diff); +#ifdef APPSPAWN_HISYSEVENT + APPSPAWN_CHECK_ONLY_EXPER(diff < FUNC_REPORT_DURATION, ReportAbnormalDuration("MOUNT", diff)); +#endif + if (ret != 0) { + APPSPAWN_LOGI("errno is: %{public}d, bind mount %{public}s to %{public}s", errno, arg->srcPath, arg->destPath); + if (errno == ENOENT && IsNeededCheckPathStatus(appProperty, arg->srcPath)) { + VerifyDirRecursive(arg->srcPath); + } + return ret; + } + + ret = mount(nullptr, arg->destPath, nullptr, arg->mountSharedFlag, nullptr); + if (ret != 0) { + APPSPAWN_LOGI("errno is: %{public}d, private mount to %{public}s '%{public}u' failed", + errno, arg->destPath, arg->mountSharedFlag); + if (errno == EINVAL) { + CheckMountStatus(arg->destPath); + } + return ret; + } + return 0; +} + +} // namespace AppSpawn +} // namespace OHOS \ No newline at end of file diff --git a/modules/sandbox/normal/sandbox_common.h b/modules/sandbox/normal/sandbox_common.h new file mode 100644 index 00000000..968c5edf --- /dev/null +++ b/modules/sandbox/normal/sandbox_common.h @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SANDBOX_COMMON_H +#define SANDBOX_COMMON_H + +#include +#include +#include +#include +#include "sandbox_def.h" +#include "appspawn_msg.h" +#include "appspawn_server.h" +#include "appspawn_manager.h" +#include "sandbox_shared_mount.h" +#include "json_utils.h" + +namespace OHOS { +namespace AppSpawn { + +// 挂载选项 +typedef struct SandboxMountConfig { + unsigned long mountFlags; + std::string optionsPoint; + std::string fsType; + std::string sandboxPath; + std::vector decPaths; +} SandboxMountConfig; + +typedef struct MountPointProcessParams { + const AppSpawningCtx *appProperty; // 引用属性 + bool checkFlag; // 检查标志 + std::string section; // 分区名称 + std::string sandboxRoot; // 沙箱根路径 + std::string bundleName; // 包名 +} MountPointProcessParams; + +using ArrayItemProcessor = std::function; + +class SandboxCommon { + +public: + // 加载配置文件 + static int LoadAppSandboxConfigCJson(AppSpawnMgr *content); + static int FreeAppSandboxConfigCJson(AppSpawnMgr *content); + static void StoreJsonConfig(cJSON *appSandboxConfig, SandboxCommonDef::SandboxConfigType type); + static std::vector &GetCJsonConfig(SandboxCommonDef::SandboxConfigType type); // GetJsonConfig + + static int32_t HandleArrayForeach(cJSON *arrayJson, ArrayItemProcessor processor); + + // 获取应用信息 + static std::string GetExtraInfoByType(const AppSpawningCtx *appProperty, const std::string &type); + static std::string GetSandboxRootPath(const AppSpawningCtx *appProperty, cJSON *config); // GetSbxPathByConfig + + // 文件操作 + static int CreateDirRecursive(const std::string &path, mode_t mode); // MakeDirRecursive + static void CreateDirRecursiveWithClock(const std::string &path, mode_t mode); // MakeDirRecursiveWithClock + static void SetSandboxPathChmod(cJSON *jsonConfig, std::string &sandboxRoot); // DoSandboxChmod + + // 获取挂载配置参数信息 + static uint32_t ConvertFlagStr(const std::string &flagStr); + static unsigned long GetMountFlags(cJSON *config); // GetSandboxMountFlags + static bool IsCreateSandboxPathEnabled(cJSON *json, std::string srcPath); // GetCreateSandboxPath + static bool IsTotalSandboxEnabled(const AppSpawningCtx *appProperty); // CheckTotalSandboxSwitchStatus + static bool IsAppSandboxEnabled(const AppSpawningCtx *appProperty); // CheckAppSandboxSwitchStatus + static void GetSandboxMountConfig(const AppSpawningCtx *appProperty, const std::string §ion, + cJSON *mntPoint, SandboxMountConfig &mountConfig); + + // 校验操作 + static bool HasPrivateInBundleName(const std::string &bundleName); // CheckBundleNameForPrivate + static bool IsMountSuccessful(cJSON *mntPoint); // GetCheckStatus + static int CheckBundleName(const std::string &bundleName); + static bool IsValidMountConfig(cJSON *mntPoint, const AppSpawningCtx *appProperty, + bool checkFlag); // CheckMountConfig + static bool IsPrivateSharedStatus(const std::string &bundleName, + AppSpawningCtx *appProperty); // GetSandboxPrivateSharedStatus + static int32_t CheckAppFullMountEnable(); + + // 路径处理 + static std::vector SplitString(std::string &str, const std::string &delimiter); // split + static std::string ReplaceAllVariables(std::string str, const std::string& from, + const std::string& to); // replace_all + static std::string ConvertToRealPath(const AppSpawningCtx *appProperty, std::string path); + static std::string ConvertToRealPathWithPermission(const AppSpawningCtx *appProperty, std::string path); + + // 挂载操作 + static int32_t DoAppSandboxMountOnce(const AppSpawningCtx *appProperty, const SharedMountArgs *arg); + +private: + // 加载配置文件 + static uint32_t GetSandboxNsFlags(bool isNweb); + static bool AppSandboxPidNsIsSupport(void); + static void StoreCJsonConfig(cJSON *root, SandboxCommonDef::SandboxConfigType type); + + // 文件操作 + static bool VerifyDirRecursive(const std::string &path); // CheckDirRecursive + static void CreateFileIfNotExist(const char *file); // CheckAndCreatFile + + // 获取挂载配置参数信息 + static bool GetSwitchStatus(cJSON *config); // GetSbxSwitchStatusByConfig + static unsigned long GetMountFlagsFromConfig(const std::vector &vec); + static bool IsDacOverrideEnabled(cJSON *config); // GetSandboxDacOverrideEnable + static std::string GetFsType(cJSON *config); // GetSandboxFsType + static std::string GetOptions(const AppSpawningCtx *appProperty, cJSON *config); // GetSandboxOptions + static std::vector GetDecPath(const AppSpawningCtx *appProperty, cJSON *config); // GetSandboxDecPath + + // 校验操作 + static bool IsNeededCheckPathStatus(const AppSpawningCtx *appProperty, const char *path); + static void CheckMountStatus(const std::string &path); + + // 路径处理 + static std::string ReplaceVariablePackageName(const AppSpawningCtx *appProperty, const std::string &path); + static void MakeAtomicServiceDir(const AppSpawningCtx *appProperty, std::string path, + std::string variablePackageName); + static std::string ReplaceHostUserId(const AppSpawningCtx *appProperty, const std::string &path); + static std::string ReplaceClonePackageName(const AppSpawningCtx *appProperty, const std::string &path); + static const std::string &GetArkWebPackageName(void); + +private: + static int32_t deviceTypeEnable_; + static std::map> appSandboxCJsonConfig_; // sandboxManager + typedef enum { + SANDBOX_PACKAGENAME_DEFAULT = 0, + SANDBOX_PACKAGENAME_CLONE, + SANDBOX_PACKAGENAME_EXTENSION, + SANDBOX_PACKAGENAME_CLONE_AND_EXTENSION, + SANDBOX_PACKAGENAME_ATOMIC_SERVICE, + } SandboxVarPackageNameType; +}; + +} // namespace AppSpawn +} // namespace OHOS + +#endif // SANDBOX_COMMON_H \ No newline at end of file diff --git a/modules/sandbox/normal/sandbox_core.cpp b/modules/sandbox/normal/sandbox_core.cpp new file mode 100644 index 00000000..a9a85f41 --- /dev/null +++ b/modules/sandbox/normal/sandbox_core.cpp @@ -0,0 +1,1449 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sandbox_core.h" + +#include +#include +#include +#include +#include +#include +#include "securec.h" +#include "appspawn_manager.h" +#include "appspawn_trace.h" +#include "appspawn_utils.h" +#include "sandbox_dec.h" +#include "sandbox_def.h" +#ifdef APPSPAWN_HISYSEVENT +#include "hisysevent_adapter.h" +#endif + +#ifdef WITH_DLP +#include "dlp_fuse_fd.h" +#endif + +namespace OHOS { +namespace AppSpawn { + +bool SandboxCore::NeedNetworkIsolated(AppSpawningCtx *property) +{ + int developerMode = IsDeveloperModeOpen(); + if (CheckAppMsgFlagsSet(property, APP_FLAGS_ISOLATED_SANDBOX) && !developerMode) { + return true; + } + + if (CheckAppMsgFlagsSet(property, APP_FLAGS_ISOLATED_NETWORK)) { + std::string extensionType = SandboxCommon::GetExtraInfoByType(property, MSG_EXT_NAME_EXTENSION_TYPE); + if (extensionType.length() == 0 || !developerMode) { + return true; + } + } + + return false; +} + +int SandboxCore::EnableSandboxNamespace(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags) +{ + StartAppspawnTrace("EnableSandboxNamespace"); +#ifdef APPSPAWN_HISYSEVENT + struct timespec startClock = {0}; + clock_gettime(CLOCK_MONOTONIC, &startClock); +#endif + int rc = unshare(sandboxNsFlags); +#ifdef APPSPAWN_HISYSEVENT + struct timespec endClock = {0}; + clock_gettime(CLOCK_MONOTONIC, &endClock); + uint64_t diff = DiffTime(&startClock, &endClock); + APPSPAWN_CHECK_ONLY_EXPER(diff < FUNC_REPORT_DURATION, ReportAbnormalDuration("unshare", diff)); +#endif + APPSPAWN_CHECK(rc == 0, return rc, "unshare %{public}s failed, err %{public}d", GetBundleName(appProperty), errno); + + if ((sandboxNsFlags & CLONE_NEWNET) == CLONE_NEWNET) { + rc = EnableNewNetNamespace(); + APPSPAWN_CHECK(rc == 0, return rc, "Set %{public}s new netnamespace failed", GetBundleName(appProperty)); + } + FinishAppspawnTrace(); + return 0; +} + +uint32_t SandboxCore::GetAppMsgFlags(const AppSpawningCtx *property) +{ + APPSPAWN_CHECK(property != nullptr && property->message != nullptr, + return 0, "Invalid property for name %{public}u", TLV_MSG_FLAGS); + AppSpawnMsgFlags *msgFlags = (AppSpawnMsgFlags *)GetAppSpawnMsgInfo(property->message, TLV_MSG_FLAGS); + APPSPAWN_CHECK(msgFlags != nullptr, + return 0, "No TLV_MSG_FLAGS in msg %{public}s", property->message->msgHeader.processName); + return msgFlags->flags[0]; +} + +bool SandboxCore::CheckMountFlag(const AppSpawningCtx *appProperty, const std::string bundleName, + cJSON *appConfig) +{ + const char *flagChr = GetStringFromJsonObj(appConfig, SandboxCommonDef::g_flags); + if (flagChr == nullptr) { + return false; + } + std::string flagStr(flagChr); + if (((SandboxCommon::ConvertFlagStr(flagStr) & GetAppMsgFlags(appProperty)) != 0) && + bundleName.find("wps") != std::string::npos) { + return true; + } + return false; +} + +void SandboxCore::UpdateMsgFlagsWithPermission(AppSpawningCtx *appProperty) +{ + int32_t processIndex = GetPermissionIndex(nullptr, SandboxCommonDef::GET_ALL_PROCESSES_MODE.c_str()); + if ((CheckAppPermissionFlagSet(appProperty, static_cast(processIndex)) == 0)) { + APPSPAWN_LOGV("Don't need set GET_ALL_PROCESSES_MODE flag"); + return; + } + + int ret = SetAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_GET_ALL_PROCESSES); + if (ret != 0) { + APPSPAWN_LOGV("Set GET_ALL_PROCESSES_MODE flag failed"); + } +} + +int32_t SandboxCore::UpdatePermissionFlags(AppSpawningCtx *appProperty) +{ + int32_t index = 0; + int32_t appFullMountStatus = SandboxCommon::CheckAppFullMountEnable(); + if (appFullMountStatus == SandboxCommonDef::FILE_CROSS_APP_STATUS) { + index = GetPermissionIndex(nullptr, SandboxCommonDef::FILE_CROSS_APP_MODE.c_str()); + } else if (appFullMountStatus == SandboxCommonDef::FILE_ACCESS_COMMON_DIR_STATUS) { + index = GetPermissionIndex(nullptr, SandboxCommonDef::FILE_ACCESS_COMMON_DIR_MODE.c_str()); + } + int32_t userFileIndex = GetPermissionIndex(nullptr, SandboxCommonDef::READ_WRITE_USER_FILE_MODE.c_str()); + int32_t fileMgrIndex = GetPermissionIndex(nullptr, SandboxCommonDef::FILE_ACCESS_MANAGER_MODE.c_str()); + if ((CheckAppPermissionFlagSet(appProperty, static_cast(userFileIndex)) != 0) && + (CheckAppPermissionFlagSet(appProperty, static_cast(fileMgrIndex)) != 0)) { + APPSPAWN_LOGE("invalid msg request."); + return -1; + } + if (index > 0 && (fileMgrIndex > 0 && userFileIndex > 0) && + (CheckAppPermissionFlagSet(appProperty, static_cast(userFileIndex)) == 0) && + (CheckAppPermissionFlagSet(appProperty, static_cast(fileMgrIndex)) == 0)) { + return SetAppPermissionFlags(appProperty, index); + } + return 0; +} + +std::string SandboxCore::GetSandboxPath(const AppSpawningCtx *appProperty, cJSON *mntPoint, + const std::string §ion, std::string sandboxRoot) +{ + std::string sandboxPath = ""; + const char *tmpSandboxPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_sandBoxPath); + if (tmpSandboxPathChr == nullptr) { + return ""; + } + std::string tmpSandboxPath(tmpSandboxPathChr); + if (section.compare(SandboxCommonDef::g_permissionPrefix) == 0) { + sandboxPath = sandboxRoot + SandboxCommon::ConvertToRealPathWithPermission(appProperty, tmpSandboxPath); + } else { + sandboxPath = sandboxRoot + SandboxCommon::ConvertToRealPath(appProperty, tmpSandboxPath); + } + return sandboxPath; +} + +int32_t SandboxCore::DoDlpAppMountStrategy(const AppSpawningCtx *appProperty, const std::string &srcPath, + const std::string &sandboxPath, const std::string &fsType, unsigned long mountFlags) +{ + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (dacInfo == nullptr) { + return -1; + } + + // umount fuse path, make sure that sandbox path is not a mount point + umount2(sandboxPath.c_str(), MNT_DETACH); + + int fd = open("/dev/fuse", O_RDWR); + APPSPAWN_CHECK(fd != -1, return -EINVAL, "open /dev/fuse failed, errno is %{public}d", errno); + + char options[SandboxCommonDef::OPTIONS_MAX_LEN]; + (void)sprintf_s(options, sizeof(options), "fd=%d," + "rootmode=40000,user_id=%u,group_id=%u,allow_other," + "context=\"u:object_r:dlp_fuse_file:s0\"," + "fscontext=u:object_r:dlp_fuse_file:s0", + fd, dacInfo->uid, dacInfo->gid); + + // To make sure destinationPath exist + (void)SandboxCommon::CreateDirRecursive(sandboxPath, SandboxCommonDef::FILE_MODE); + + int ret = 0; +#ifndef APPSPAWN_TEST + APPSPAWN_LOGV("Bind mount %{public}s to %{public}s '%{public}s' '%{public}lu' '%{public}s'", + srcPath.c_str(), sandboxPath.c_str(), fsType.c_str(), mountFlags, options); + ret = mount(srcPath.c_str(), sandboxPath.c_str(), fsType.c_str(), mountFlags, options); + APPSPAWN_CHECK(ret == 0, close(fd); + return ret, "DoDlpAppMountStrategy failed, bind mount %{public}s to %{public}s failed %{public}d", + srcPath.c_str(), sandboxPath.c_str(), errno); + + ret = mount(nullptr, sandboxPath.c_str(), nullptr, MS_SHARED, nullptr); + APPSPAWN_CHECK(ret == 0, close(fd); + return ret, "errno is: %{public}d, private mount to %{public}s failed", errno, sandboxPath.c_str()); +#endif + /* set DLP_FUSE_FD */ +#ifdef WITH_DLP + SetDlpFuseFd(fd); +#endif + return fd; +} + +int32_t SandboxCore::HandleSpecialAppMount(const AppSpawningCtx *appProperty, const std::string &srcPath, + const std::string &sandboxPath, const std::string &fsType, unsigned long mountFlags) +{ + std::string bundleName = GetBundleName(appProperty); + std::string processName = GetProcessName(appProperty); + /* dlp application mount strategy */ + /* dlp is an example, we should change to real bundle name later */ + if (bundleName.find(SandboxCommonDef::g_dlpBundleName) != std::string::npos && + processName.compare(SandboxCommonDef::g_dlpBundleName) == 0) { + if (!fsType.empty()) { + return DoDlpAppMountStrategy(appProperty, srcPath, sandboxPath, fsType, mountFlags); + } + } + return -1; +} + +cJSON *SandboxCore::GetPrivateJsonInfo(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *firstPrivate = GetFirstCommonConfig(wholeConfig, SandboxCommonDef::g_privatePrefix); + if (!firstPrivate) { + return nullptr; + } + + const char *bundleName = GetBundleName(appProperty); + return GetFirstSubConfig(firstPrivate, bundleName); +} + +int32_t SandboxCore::DoSandboxFilePrivateBind(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *bundleNameInfo = GetPrivateJsonInfo(appProperty, wholeConfig); + if (bundleNameInfo == nullptr) { + return 0; + } + (void)DoAddGid((AppSpawningCtx *)appProperty, bundleNameInfo, "", SandboxCommonDef::g_privatePrefix); + return DoAllMntPointsMount(appProperty, bundleNameInfo, nullptr, SandboxCommonDef::g_privatePrefix); +} + +int32_t SandboxCore::DoSandboxFilePrivateSymlink(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *bundleNameInfo = GetPrivateJsonInfo(appProperty, wholeConfig); + if (bundleNameInfo == nullptr) { + return 0; + } + return DoAllSymlinkPointslink(appProperty, bundleNameInfo); +} + +int32_t SandboxCore::DoSandboxFilePrivateFlagsPointHandle(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *bundleNameInfo = GetPrivateJsonInfo(appProperty, wholeConfig); + if (bundleNameInfo == nullptr) { + return 0; + } + return HandleFlagsPoint(appProperty, bundleNameInfo); +} + +int32_t SandboxCore::SetPrivateAppSandboxProperty_(const AppSpawningCtx *appProperty, cJSON *config) +{ + int ret = DoSandboxFilePrivateBind(appProperty, config); + APPSPAWN_CHECK(ret == 0, return ret, "DoSandboxFilePrivateBind failed"); + + ret = DoSandboxFilePrivateSymlink(appProperty, config); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "DoSandboxFilePrivateSymlink failed"); + + ret = DoSandboxFilePrivateFlagsPointHandle(appProperty, config); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "DoSandboxFilePrivateFlagsPointHandle failed"); + + return ret; +} + +int32_t SandboxCore::DoSandboxFilePermissionBind(AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *permission = cJSON_GetObjectItemCaseSensitive(wholeConfig, SandboxCommonDef::g_permissionPrefix); + if (!permission || !cJSON_IsArray(permission)) { + return 0; + } + + auto processor = [&appProperty](cJSON *item) { + cJSON *permissionChild = item->child; + while (permissionChild != nullptr) { + int index = GetPermissionIndex(nullptr, permissionChild->string); + APPSPAWN_LOGV("DoSandboxFilePermissionBind %{public}s index %{public}d", permissionChild->string, index); + if (CheckAppPermissionFlagSet(appProperty, static_cast(index)) == 0) { + permissionChild = permissionChild->next; + continue; + } + DoAddGid(appProperty, permissionChild, permissionChild->string, SandboxCommonDef::g_permissionPrefix); + cJSON *permissionMountPaths = cJSON_GetArrayItem(permissionChild, 0); + if (!permissionMountPaths) { + permissionChild = permissionChild->next; + continue; + } + DoAddGid(appProperty, permissionMountPaths, permissionChild->string, SandboxCommonDef::g_permissionPrefix); + DoAllMntPointsMount(appProperty, permissionMountPaths, permissionChild->string, + SandboxCommonDef::g_permissionPrefix); + + permissionChild = permissionChild->next; + } + return 0; + }; + + return SandboxCommon::HandleArrayForeach(permission, processor); +} + +int32_t SandboxCore::SetPermissionAppSandboxProperty_(AppSpawningCtx *appProperty, cJSON *config) +{ + int ret = DoSandboxFilePermissionBind(appProperty, config); + APPSPAWN_CHECK(ret == 0, return ret, "DoSandboxFilePermissionBind failed"); + return ret; +} + +cJSON *SandboxCore::GetFirstCommonConfig(cJSON *wholeConfig, const char *prefix) +{ + cJSON *commonConfig = cJSON_GetObjectItemCaseSensitive(wholeConfig, prefix); + if (!commonConfig || !cJSON_IsArray(commonConfig)) { + return nullptr; + } + + return cJSON_GetArrayItem(commonConfig, 0); +} + +cJSON *SandboxCore::GetFirstSubConfig(cJSON *parent, const char *key) +{ + cJSON *config = cJSON_GetObjectItemCaseSensitive(parent, key); + if (!config || !cJSON_IsArray(config)) { + return nullptr; + } + + return cJSON_GetArrayItem(config, 0); +} + +int32_t SandboxCore::DoSandboxFileCommonBind(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *firstCommon = GetFirstCommonConfig(wholeConfig, SandboxCommonDef::g_commonPrefix); + if (!firstCommon) { + return 0; + } + + cJSON *appBaseConfig = GetFirstSubConfig(firstCommon, SandboxCommonDef::g_appBase); + if (!appBaseConfig) { + return 0; + } + + int ret = DoAllMntPointsMount(appProperty, appBaseConfig, nullptr, SandboxCommonDef::g_appBase); + if (ret) { + return ret; + } + + cJSON *appResourcesConfig = GetFirstSubConfig(firstCommon, SandboxCommonDef::g_appResources); + if (!appResourcesConfig) { + return 0; + } + ret = DoAllMntPointsMount(appProperty, appResourcesConfig, nullptr, SandboxCommonDef::g_appResources); + return ret; +} + +int32_t SandboxCore::DoSandboxFileCommonSymlink(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *firstCommon = GetFirstCommonConfig(wholeConfig, SandboxCommonDef::g_commonPrefix); + if (!firstCommon) { + return 0; + } + + cJSON *appBaseConfig = GetFirstSubConfig(firstCommon, SandboxCommonDef::g_appBase); + if (!appBaseConfig) { + return 0; + } + + int ret = DoAllSymlinkPointslink(appProperty, appBaseConfig); + if (ret) { + return ret; + } + + cJSON *appResourcesConfig = GetFirstSubConfig(firstCommon, SandboxCommonDef::g_appResources); + if (!appResourcesConfig) { + return 0; + } + ret = DoAllSymlinkPointslink(appProperty, appResourcesConfig); + return ret; +} + +int32_t SandboxCore::DoSandboxFileCommonFlagsPointHandle(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *firstCommon = GetFirstCommonConfig(wholeConfig, SandboxCommonDef::g_commonPrefix); + if (!firstCommon) { + return 0; + } + + cJSON *appResoucesConfig = GetFirstSubConfig(firstCommon, SandboxCommonDef::appResouces); + if (!appResoucesConfig) { + return 0; + } + + return HandleFlagsPoint(appProperty, appResoucesConfig); +} + +int32_t SandboxCore::SetCommonAppSandboxProperty_(const AppSpawningCtx *appProperty, cJSON *config) +{ + int rc = 0; + rc = DoSandboxFileCommonBind(appProperty, config); + APPSPAWN_CHECK(rc == 0, return rc, "DoSandboxFileCommonBind failed, %{public}s", GetBundleName(appProperty)); + + // if sandbox switch is off, don't do symlink work again + if (SandboxCommon::IsAppSandboxEnabled(appProperty) == true && + (SandboxCommon::IsTotalSandboxEnabled(appProperty) == true)) { + rc = DoSandboxFileCommonSymlink(appProperty, config); + APPSPAWN_CHECK(rc == 0, return rc, "DoSandboxFileCommonSymlink failed, %{public}s", GetBundleName(appProperty)); + } + + rc = DoSandboxFileCommonFlagsPointHandle(appProperty, config); + APPSPAWN_CHECK_ONLY_LOG(rc == 0, "DoSandboxFilePrivateFlagsPointHandle failed"); + + return rc; +} + +static inline bool CheckPath(const std::string& name) +{ + return !name.empty() && name != "." && name != ".." && name.find("/") == std::string::npos; +} + +static inline cJSON *GetJsonObjFromProperty(const AppSpawningCtx *appProperty, const char *name) +{ + uint32_t size = 0; + const char *extInfo = (char *)(GetAppSpawnMsgExtInfo(appProperty->message, name, &size)); + if (size == 0 || extInfo == nullptr) { + return nullptr; + } + APPSPAWN_LOGV("Get json name %{public}s value %{public}s", name, extInfo); + cJSON *root = cJSON_Parse(extInfo); + APPSPAWN_CHECK(root != nullptr, return nullptr, "Invalid ext info %{public}s for %{public}s", extInfo, name); + return root; +} + +int32_t SandboxCore::MountAllHsp(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ + if (appProperty == nullptr || sandboxPackagePath == "") { + return 0; + } + int ret = 0; + cJSON *hspRoot = GetJsonObjFromProperty(appProperty, SandboxCommonDef::HSPLIST_SOCKET_TYPE.c_str()); + APPSPAWN_CHECK_ONLY_EXPER(hspRoot != nullptr, return 0); + + cJSON *bundles = cJSON_GetObjectItemCaseSensitive(hspRoot, "bundles"); + cJSON *modules = cJSON_GetObjectItemCaseSensitive(hspRoot, "modules"); + cJSON *versions = cJSON_GetObjectItemCaseSensitive(hspRoot, "versions"); + APPSPAWN_CHECK(bundles != nullptr && cJSON_IsArray(bundles), return -1, "MountAllHsp: invalid bundles"); + APPSPAWN_CHECK(modules != nullptr && cJSON_IsArray(modules), return -1, "MountAllHsp: invalid modules"); + APPSPAWN_CHECK(versions != nullptr && cJSON_IsArray(versions), return -1, "MountAllHsp: invalid versions"); + int count = cJSON_GetArraySize(bundles); + APPSPAWN_CHECK(count == cJSON_GetArraySize(modules), return -1, "MountAllHsp: sizes are not same"); + APPSPAWN_CHECK(count == cJSON_GetArraySize(versions), return -1, "MountAllHsp: sizes are not same"); + + APPSPAWN_LOGI("MountAllHsp app: %{public}s, count: %{public}d", GetBundleName(appProperty), count); + for (int i = 0; i < count; i++) { + const char *libBundleName = cJSON_GetStringValue(cJSON_GetArrayItem(bundles, i)); + const char *libModuleName = cJSON_GetStringValue(cJSON_GetArrayItem(modules, i)); + const char *libVersion = cJSON_GetStringValue(cJSON_GetArrayItem(versions, i)); + APPSPAWN_CHECK(CheckPath(libBundleName) && CheckPath(libModuleName) && CheckPath(libVersion), + return -1, "MountAllHsp: path error"); + + std::string libPhysicalPath = SandboxCommonDef::g_physicalAppInstallPath + libBundleName + "/" + + libVersion + "/" + libModuleName; + std::string mntPath = + sandboxPackagePath + SandboxCommonDef::g_sandboxHspInstallPath + libBundleName + "/" + libModuleName; + SharedMountArgs arg = { + .srcPath = libPhysicalPath.c_str(), + .destPath = mntPath.c_str() + }; + ret = SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); + APPSPAWN_CHECK(ret == 0, return 0, "mount library failed %{public}d", ret); + } + cJSON_Delete(hspRoot); + return 0; +} + +int32_t SandboxCore::MountAllGroup(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ + if (appProperty == nullptr || sandboxPackagePath == "") { + return 0; + } + cJSON *dataGroupRoot = GetJsonObjFromProperty(appProperty, SandboxCommonDef::DATA_GROUP_SOCKET_TYPE.c_str()); + APPSPAWN_CHECK_ONLY_EXPER(dataGroupRoot != nullptr, return 0); + + mode_t mountSharedFlag = MS_SLAVE; + if (CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX)) { + APPSPAWN_LOGV("Data group flags is isolated"); + mountSharedFlag |= MS_REMOUNT | MS_NODEV | MS_RDONLY | MS_BIND; + } + + auto processor = [&appProperty, &sandboxPackagePath, &mountSharedFlag](cJSON *item) { + APPSPAWN_CHECK(IsValidDataGroupItem(item), return -1, "MountAllGroup: data group item error"); + const char *srcPathChr = GetStringFromJsonObj(item, SandboxCommonDef::g_groupList_key_dir.c_str()); + if (srcPathChr == nullptr) { + return 0; + } + std::string srcPath(srcPathChr); + APPSPAWN_CHECK(!CheckPath(srcPath), return -1, "MountAllGroup: path error"); + const char *uuidChr = GetStringFromJsonObj(item, SandboxCommonDef::g_groupList_key_uuid.c_str()); + if (uuidChr == nullptr) { + return 0; + } + std::string uuidStr(uuidChr); + + int elxValue = GetElxInfoFromDir(srcPath.c_str()); + APPSPAWN_CHECK((elxValue >= EL2 && elxValue < ELX_MAX), return -1, "Get elx value failed"); + + const DataGroupSandboxPathTemplate *templateItem = GetDataGroupArgTemplate(elxValue); + APPSPAWN_CHECK(templateItem != nullptr, return -1, "Get data group arg template failed"); + + // If permission isn't null, need check permission flag + if (templateItem->permission != nullptr) { + int index = GetPermissionIndex(nullptr, templateItem->permission); + APPSPAWN_LOGV("mount dir no lock mount permission flag %{public}d", index); + if (CheckAppPermissionFlagSet(appProperty, static_cast(index)) == 0) { + return 0; + } + } + + std::string mntPath = sandboxPackagePath + templateItem->sandboxPath + uuidStr; + SharedMountArgs arg = { + .srcPath = srcPath.c_str(), + .destPath = mntPath.c_str(), + .mountSharedFlag = mountSharedFlag + }; + int result = SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); + if (result != 0) { + APPSPAWN_LOGE("mount el%{public}d datagroup failed", elxValue); + } + return 0; + }; + int ret = SandboxCommon::HandleArrayForeach(dataGroupRoot, processor); + cJSON_Delete(dataGroupRoot); + return ret; +} + +int32_t SandboxCore::ProcessMountPoint(cJSON *mntPoint, MountPointProcessParams ¶ms) +{ + + APPSPAWN_CHECK_ONLY_EXPER(SandboxCommon::IsValidMountConfig(mntPoint, params.appProperty, params.checkFlag), + return 0); + const char *srcPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_srcPath); + const char *sandboxPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_sandBoxPath); + if (srcPathChr == nullptr || sandboxPathChr == nullptr) { + return 0; + } + std::string srcPath(srcPathChr); + std::string sandboxPath(sandboxPathChr); + srcPath = SandboxCommon::ConvertToRealPath(params.appProperty, srcPath); + APPSPAWN_CHECK_ONLY_EXPER(SandboxCommon::IsCreateSandboxPathEnabled(mntPoint, srcPath), return 0); + sandboxPath = GetSandboxPath(params.appProperty, mntPoint, params.section, params.sandboxRoot); + SandboxMountConfig mountConfig = {0}; + SandboxCommon::GetSandboxMountConfig(params.appProperty, params.section, mntPoint, mountConfig); + SharedMountArgs arg = { + .srcPath = srcPath.c_str(), + .destPath = sandboxPath.c_str(), + .fsType = mountConfig.fsType.c_str(), + .mountFlags = SandboxCommon::GetMountFlags(mntPoint), + .options = mountConfig.optionsPoint.c_str(), + .mountSharedFlag = + GetBoolValueFromJsonObj(mntPoint, SandboxCommonDef::g_mountSharedFlag, false) ? MS_SHARED : MS_SLAVE + }; + + /* if app mount failed for special strategy, we need deal with common mount config */ + int ret = HandleSpecialAppMount(params.appProperty, arg.srcPath, arg.destPath, arg.fsType, arg.mountFlags); + if (ret < 0) { + ret = SandboxCommon::DoAppSandboxMountOnce(params.appProperty, &arg); + } + APPSPAWN_CHECK(ret == 0 || !SandboxCommon::IsMountSuccessful(mntPoint), +#ifdef APPSPAWN_HISYSEVENT + ReportMountFail(params.bundleName.c_str(), arg.srcPath, arg.destPath, errno); + ret = APPSPAWN_SANDBOX_MOUNT_FAIL; +#endif + return ret, + "DoAppSandboxMountOnce section %{public}s failed, %{public}s", params.section.c_str(), arg.destPath); + SetDecPolicyWithPermission(params.appProperty, mountConfig); + SandboxCommon::SetSandboxPathChmod(mntPoint, params.sandboxRoot); + return 0; +} + +int32_t SandboxCore::DoAllMntPointsMount(const AppSpawningCtx *appProperty, cJSON *appConfig, + const char *typeName, const std::string §ion) +{ + std::string bundleName = GetBundleName(appProperty); + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(appConfig, SandboxCommonDef::g_mountPrefix); + if (mountPoints == nullptr || !cJSON_IsArray(mountPoints)) { + APPSPAWN_LOGI("mount config is not found in %{public}s, app name is %{public}s", + section.c_str(), bundleName.c_str()); + return 0; + } + + std::string sandboxRoot = SandboxCommon::GetSandboxRootPath(appProperty, appConfig); + bool checkFlag = CheckMountFlag(appProperty, bundleName, appConfig); + MountPointProcessParams mountPointParams = { + .appProperty = appProperty, + .checkFlag = checkFlag, + .section = section, + .sandboxRoot = sandboxRoot, + .bundleName = bundleName + }; + + auto processor = [&mountPointParams](cJSON *mntPoint) { + return ProcessMountPoint(mntPoint, mountPointParams); + }; + + return SandboxCommon::HandleArrayForeach(mountPoints, processor); +} + +int32_t SandboxCore::DoAddGid(AppSpawningCtx *appProperty, cJSON *appConfig, + const char *permissionName, const std::string §ion) +{ + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (dacInfo == nullptr) { + return 0; + } + + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(appConfig, SandboxCommonDef::g_gidPrefix); + if (mountPoints == nullptr || !cJSON_IsArray(mountPoints)) { + return 0; + } + + std::string bundleName = GetBundleName(appProperty); + auto processor = [&dacInfo](cJSON *item) { + gid_t gid = 0; + if (cJSON_IsNumber(item)) { + gid = (gid_t)cJSON_GetNumberValue(item); + } + if (gid <= 0) { + return 0; + } + if (dacInfo->gidCount < APP_MAX_GIDS) { + dacInfo->gidTable[dacInfo->gidCount++] = gid; + } + return 0; + }; + + return SandboxCommon::HandleArrayForeach(mountPoints, processor); +} + +int32_t SandboxCore::DoAllSymlinkPointslink(const AppSpawningCtx *appProperty, cJSON *appConfig) +{ + cJSON *symlinkPoints = cJSON_GetObjectItemCaseSensitive(appConfig, SandboxCommonDef::g_symlinkPrefix); + if (symlinkPoints == nullptr || !cJSON_IsArray(symlinkPoints)) { + APPSPAWN_LOGV("symlink config is not found"); + return 0; + } + + std::string sandboxRoot = SandboxCommon::GetSandboxRootPath(appProperty, appConfig); + auto processor = [&appProperty, &sandboxRoot](cJSON *item) { + const char *targetNameChr = GetStringFromJsonObj(item, SandboxCommonDef::g_targetName); + const char *linkNameChr = GetStringFromJsonObj(item, SandboxCommonDef::g_linkName); + if (targetNameChr == nullptr || linkNameChr == nullptr) { + return 0; + } + std::string targetName(targetNameChr); + std::string linkName(linkNameChr); + targetName = SandboxCommon::ConvertToRealPath(appProperty, targetName); + linkName = sandboxRoot + SandboxCommon::ConvertToRealPath(appProperty, linkName); + int ret = symlink(targetName.c_str(), linkName.c_str()); + if (ret && errno != EEXIST && SandboxCommon::IsMountSuccessful(item)) { + APPSPAWN_LOGE("errno is %{public}d, symlink failed, %{public}s", errno, linkName.c_str()); + return -1; + } + SandboxCommon::SetSandboxPathChmod(item, sandboxRoot); + return 0; + }; + + return SandboxCommon::HandleArrayForeach(symlinkPoints, processor); +} + +int32_t SandboxCore::DoSandboxRootFolderCreateAdapt(std::string &sandboxPackagePath) +{ +#ifndef APPSPAWN_TEST + int rc = mount(nullptr, "/", nullptr, MS_REC | MS_SLAVE, nullptr); + APPSPAWN_CHECK(rc == 0, return rc, "set propagation slave failed"); +#endif + (void)SandboxCommon::CreateDirRecursive(sandboxPackagePath, SandboxCommonDef::FILE_MODE); + + // bind mount "/" to /mnt/sandbox// path + // rootfs: to do more resources bind mount here to get more strict resources constraints +#ifndef APPSPAWN_TEST + rc = mount("/", sandboxPackagePath.c_str(), nullptr, SandboxCommonDef::BASIC_MOUNT_FLAGS, nullptr); + APPSPAWN_CHECK(rc == 0, return rc, "mount bind / failed, %{public}d", errno); +#endif + return 0; +} + +int32_t SandboxCore::DoSandboxRootFolderCreate(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ +#ifndef APPSPAWN_TEST + int rc = mount(nullptr, "/", nullptr, MS_REC | MS_SLAVE, nullptr); + if (rc) { + return rc; + } +#endif + SharedMountArgs arg = { + .srcPath = sandboxPackagePath.c_str(), + .destPath = sandboxPackagePath.c_str() + }; + SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); + + return 0; +} + +int32_t SandboxCore::HandleFlagsPoint(const AppSpawningCtx *appProperty, cJSON *appConfig) +{ + cJSON *flagsPoints = cJSON_GetObjectItemCaseSensitive(appConfig, SandboxCommonDef::g_flagePoint); + if (flagsPoints == nullptr || !cJSON_IsArray(flagsPoints)) { + APPSPAWN_LOGV("flag points config is not found"); + return 0; + } + + auto processor = [&appProperty](cJSON *item) { + const char *flagsChr = GetStringFromJsonObj(item, SandboxCommonDef::g_flags); + std::string flagsStr(flagsChr); + uint32_t flag = SandboxCommon::ConvertFlagStr(flagsStr); + if ((GetAppMsgFlags(appProperty) & flag) == 0) { + return 0; + } + return DoAllMntPointsMount(appProperty, item, nullptr, SandboxCommonDef::g_flagePoint); + }; + return SandboxCommon::HandleArrayForeach(flagsPoints, processor); +} + +int32_t SandboxCore::SetOverlayAppSandboxProperty(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ + int ret = 0; + if (!CheckAppMsgFlagsSet(appProperty, APP_FLAGS_OVERLAY)) { + return ret; + } + + std::string overlayInfo = SandboxCommon::GetExtraInfoByType(appProperty, SandboxCommonDef::OVERLAY_SOCKET_TYPE); + std::set mountedSrcSet; + std::vector splits = SandboxCommon::SplitString(overlayInfo, SandboxCommonDef::g_overlayDecollator); + std::string sandboxOverlayPath = sandboxPackagePath + SandboxCommonDef::g_overlayPath; + for (auto hapPath : splits) { + size_t pathIndex = hapPath.find_last_of(SandboxCommonDef::g_fileSeparator); + if (pathIndex == std::string::npos) { + continue; + } + std::string srcPath = hapPath.substr(0, pathIndex); + if (mountedSrcSet.find(srcPath) != mountedSrcSet.end()) { + APPSPAWN_LOGV("%{public}s have mounted before, no need to mount twice.", srcPath.c_str()); + continue; + } + + auto bundleNameIndex = srcPath.find_last_of(SandboxCommonDef::g_fileSeparator); + std::string destPath = sandboxOverlayPath + srcPath.substr(bundleNameIndex + 1, srcPath.length()); + SharedMountArgs arg = { + .srcPath = srcPath.c_str(), + .destPath = destPath.c_str() + }; + int32_t retMount = SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); + if (retMount != 0) { + APPSPAWN_LOGE("fail to mount overlay path, src is %{public}s.", hapPath.c_str()); + ret = retMount; + } + + mountedSrcSet.emplace(srcPath); + } + return ret; +} + +int32_t SandboxCore::SetBundleResourceAppSandboxProperty(const AppSpawningCtx *appProperty, + std::string &sandboxPackagePath) +{ + if (!CheckAppMsgFlagsSet(appProperty, APP_FLAGS_BUNDLE_RESOURCES)) { + return 0; + } + + std::string destPath = sandboxPackagePath + SandboxCommonDef::g_bundleResourceDestPath; + SharedMountArgs arg = { + .srcPath = SandboxCommonDef::g_bundleResourceSrcPath.c_str(), + .destPath = destPath.c_str() + }; + return SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); +} + +int32_t SandboxCore::SetCommonAppSandboxProperty(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ + int ret = 0; + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANBOX_APP_JSON_CONFIG; + + for (auto& jsonConfig : SandboxCommon::GetCJsonConfig(type)) { + ret = SetCommonAppSandboxProperty_(appProperty, jsonConfig); + APPSPAWN_CHECK(ret == 0, return ret, + "parse appdata config for common failed, %{public}s", sandboxPackagePath.c_str()); + } + + ret = MountAllHsp(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(ret == 0, return ret, "mount extraInfo failed, %{public}s", sandboxPackagePath.c_str()); + + ret = MountAllGroup(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(ret == 0, return ret, "mount groupList failed, %{public}s", sandboxPackagePath.c_str()); + + AppSpawnMsgDomainInfo *info = + reinterpret_cast(GetAppProperty(appProperty, TLV_DOMAIN_INFO)); + APPSPAWN_CHECK(info != nullptr, return -1, "No domain info %{public}s", sandboxPackagePath.c_str()); + if (strcmp(info->apl, SandboxCommonDef::APL_SYSTEM_BASIC.data()) == 0 || + strcmp(info->apl, SandboxCommonDef::APL_SYSTEM_CORE.data()) == 0 || + CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ACCESS_BUNDLE_DIR)) { + // need permission check for system app here + std::string destbundlesPath = sandboxPackagePath + SandboxCommonDef::g_dataBundles; + SharedMountArgs arg = { + .srcPath = SandboxCommonDef::g_physicalAppInstallPath.c_str(), + .destPath = destbundlesPath.c_str() + }; + SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); + } + + return 0; +} + +int32_t SandboxCore::SetPrivateAppSandboxProperty(const AppSpawningCtx *appProperty) +{ + int ret = 0; + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANBOX_APP_JSON_CONFIG; + + for (auto& config : SandboxCommon::GetCJsonConfig(type)) { + ret = SetPrivateAppSandboxProperty_(appProperty, config); + APPSPAWN_CHECK(ret == 0, return ret, "parse adddata-sandbox config failed"); + } + return ret; +} + +int32_t SandboxCore::SetPermissionAppSandboxProperty(AppSpawningCtx *appProperty) +{ + int ret = 0; + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANBOX_APP_JSON_CONFIG; + + for (auto& config : SandboxCommon::GetCJsonConfig(type)) { + ret = SetPermissionAppSandboxProperty_(appProperty, config); + APPSPAWN_CHECK(ret == 0, return ret, "parse permission config failed"); + } + return ret; +} + +int32_t SandboxCore::SetSandboxProperty(AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ + int32_t ret = 0; + const std::string bundleName = GetBundleName(appProperty); + ret = SetCommonAppSandboxProperty(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(ret == 0, return ret, "SetCommonAppSandboxProperty failed, packagename is %{public}s", + bundleName.c_str()); + if (SandboxCommon::HasPrivateInBundleName(bundleName)) { + ret = SetPrivateAppSandboxProperty(appProperty); + APPSPAWN_CHECK(ret == 0, return ret, "SetPrivateAppSandboxProperty failed, packagename is %{public}s", + bundleName.c_str()); + } + ret = SetPermissionAppSandboxProperty(appProperty); + APPSPAWN_CHECK(ret == 0, return ret, "SetPermissionAppSandboxProperty failed, packagename is %{public}s", + bundleName.c_str()); + + ret = SetOverlayAppSandboxProperty(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(ret == 0, return ret, "SetOverlayAppSandboxProperty failed, packagename is %{public}s", + bundleName.c_str()); + + ret = SetBundleResourceAppSandboxProperty(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(ret == 0, return ret, "SetBundleResourceAppSandboxProperty failed, packagename is %{public}s", + bundleName.c_str()); + APPSPAWN_LOGV("Set appsandbox property success"); + return ret; +} + +int32_t SandboxCore::SetAppSandboxProperty(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags) +{ + APPSPAWN_CHECK(appProperty != nullptr, return -1, "Invalid appspwn client"); + if (SandboxCommon::CheckBundleName(GetBundleName(appProperty)) != 0) { + return -1; + } + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (dacInfo == nullptr) { + return -1; + } + + const std::string bundleName = GetBundleName(appProperty); + cJSON *tmpJson = nullptr; + std::string sandboxPackagePath = SandboxCommon::GetSandboxRootPath(appProperty, tmpJson); + SandboxCommon::CreateDirRecursiveWithClock(sandboxPackagePath.c_str(), SandboxCommonDef::FILE_MODE); + bool sandboxSharedStatus = SandboxCommon::IsPrivateSharedStatus(bundleName, appProperty) || + (CheckAppPermissionFlagSet(appProperty, static_cast(GetPermissionIndex(nullptr, + SandboxCommonDef::ACCESS_DLP_FILE_MODE.c_str()))) != 0); + + // add pid to a new mnt namespace + int rc = EnableSandboxNamespace(appProperty, sandboxNsFlags); + APPSPAWN_CHECK(rc == 0, return rc, "unshare failed, packagename is %{public}s", bundleName.c_str()); + if (UpdatePermissionFlags(appProperty) != 0) { + APPSPAWN_LOGW("Set app permission flag fail."); + return -1; + } + UpdateMsgFlagsWithPermission(appProperty); + // check app sandbox switch + if ((SandboxCommon::IsTotalSandboxEnabled(appProperty) == false) || + (SandboxCommon::IsAppSandboxEnabled(appProperty) == false)) { + rc = DoSandboxRootFolderCreateAdapt(sandboxPackagePath); + } else if (!sandboxSharedStatus) { + rc = DoSandboxRootFolderCreate(appProperty, sandboxPackagePath); + } + APPSPAWN_CHECK(rc == 0, return rc, "DoSandboxRootFolderCreate failed, %{public}s", bundleName.c_str()); + rc = SetSandboxProperty(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(rc == 0, return rc, "SetSandboxProperty failed, %{public}s", bundleName.c_str()); + +#ifdef APPSPAWN_MOUNT_TMPSHM + MountDevShmPath(sandboxPackagePath); +#endif + +#ifndef APPSPAWN_TEST + rc = ChangeCurrentDir(sandboxPackagePath, bundleName, sandboxSharedStatus); + APPSPAWN_CHECK(rc == 0, return rc, "change current dir failed"); + APPSPAWN_LOGV("Change root dir success"); +#endif + SetDecWithDir(appProperty, dacInfo->uid / UID_BASE); + SetDecDenyWithDir(appProperty); + SetDecPolicy(); +#if defined(APPSPAWN_MOUNT_TMPSHM) && defined(WITH_SELINUX) + Restorecon(DEV_SHM_DIR); +#endif + return 0; +} + +int32_t SandboxCore::SetRenderSandboxPropertyNweb(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ + char *processType = (char *)(GetAppSpawnMsgExtInfo(appProperty->message, MSG_EXT_NAME_PROCESS_TYPE, nullptr)); + APPSPAWN_CHECK(processType != nullptr, return -1, "Invalid processType data"); + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANBOX_APP_JSON_CONFIG; + + int ret = 0; + const char *bundleNmae = GetBundleName(appProperty); + for (auto& config : SandboxCommon::GetCJsonConfig(type)) { + cJSON *firstIndividual = GetFirstCommonConfig(config, SandboxCommonDef::g_privatePrefix); + if (!firstIndividual) { + continue; + } + if (strcmp(processType, "render") == 0) { + cJSON *renderInfo = GetFirstSubConfig(firstIndividual, SandboxCommonDef::g_ohosRender.c_str()); + if (!renderInfo) { + continue; + } + ret = DoAllMntPointsMount(appProperty, renderInfo, nullptr, SandboxCommonDef::g_ohosRender); + APPSPAWN_CHECK(ret == 0, return ret, "DoAllMntPointsMount failed, %{public}s", bundleNmae); + + ret = DoAllSymlinkPointslink(appProperty, renderInfo); + APPSPAWN_CHECK(ret == 0, return ret, "DoAllSymlinkPointslink failed, %{public}s", bundleNmae); + + ret = HandleFlagsPoint(appProperty, renderInfo); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "HandleFlagsPoint for render-sandbox failed, %{public}s", bundleNmae); + } else if (strcmp(processType, "gpu") == 0) { + cJSON *gpuInfo = GetFirstSubConfig(firstIndividual, SandboxCommonDef::g_ohosGpu.c_str()); + if (!gpuInfo) { + continue; + } + ret = DoAllMntPointsMount(appProperty, gpuInfo, nullptr, SandboxCommonDef::g_ohosGpu); + APPSPAWN_CHECK(ret == 0, return ret, "DoAllMntPointsMount failed, %{public}s", bundleNmae); + + ret = DoAllSymlinkPointslink(appProperty, gpuInfo); + APPSPAWN_CHECK(ret == 0, return ret, "DoAllSymlinkPointslink failed, %{public}s", bundleNmae); + + ret = HandleFlagsPoint(appProperty, gpuInfo); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "HandleFlagsPoint for gpu-sandbox failed, %{public}s", bundleNmae); + } + } + + return 0; +} + +int32_t SandboxCore::SetAppSandboxPropertyNweb(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags) +{ + APPSPAWN_CHECK(appProperty != nullptr, return -1, "Invalid appspwn client"); + if (SandboxCommon::CheckBundleName(GetBundleName(appProperty)) != 0) { + return -1; + } + std::string sandboxPackagePath = SandboxCommonDef::g_sandBoxRootDirNweb; + const std::string bundleName = GetBundleName(appProperty); + bool sandboxSharedStatus = SandboxCommon::IsPrivateSharedStatus(bundleName, appProperty); + sandboxPackagePath += bundleName; + SandboxCommon::CreateDirRecursiveWithClock(sandboxPackagePath.c_str(), SandboxCommonDef::FILE_MODE); + + // add pid to a new mnt namespace + int rc = EnableSandboxNamespace(appProperty, sandboxNsFlags); + APPSPAWN_CHECK(rc == 0, return rc, "unshare failed, packagename is %{public}s", bundleName.c_str()); + + // check app sandbox switch + if ((SandboxCommon::IsTotalSandboxEnabled(appProperty) == false) || + (SandboxCommon::IsAppSandboxEnabled(appProperty) == false)) { + rc = DoSandboxRootFolderCreateAdapt(sandboxPackagePath); + } else if (!sandboxSharedStatus) { + rc = DoSandboxRootFolderCreate(appProperty, sandboxPackagePath); + } + APPSPAWN_CHECK(rc == 0, return rc, "DoSandboxRootFolderCreate failed, %{public}s", bundleName.c_str()); + // rendering process can be created by different apps, + // and the bundle names of these apps are different, + // so we can't use the method SetPrivateAppSandboxProperty + // which mount dirs by using bundle name. + rc = SetRenderSandboxPropertyNweb(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(rc == 0, return rc, "SetRenderSandboxPropertyNweb for %{public}s failed", bundleName.c_str()); + + rc = SetOverlayAppSandboxProperty(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(rc == 0, return rc, "SetOverlayAppSandboxProperty for %{public}s failed", bundleName.c_str()); + + rc = SetBundleResourceAppSandboxProperty(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(rc == 0, return rc, "SetBundleResourceAppSandboxProperty for %{public}s failed", bundleName.c_str()); + +#ifndef APPSPAWN_TEST + rc = chdir(sandboxPackagePath.c_str()); + APPSPAWN_CHECK(rc == 0, return rc, "chdir %{public}s failed, err %{public}d", sandboxPackagePath.c_str(), errno); + + if (sandboxSharedStatus) { + rc = chroot(sandboxPackagePath.c_str()); + APPSPAWN_CHECK(rc == 0, return rc, "chroot %{public}s failed, err %{public}d", + sandboxPackagePath.c_str(), errno); + return 0; + } + + rc = syscall(SYS_pivot_root, sandboxPackagePath.c_str(), sandboxPackagePath.c_str()); + APPSPAWN_CHECK(rc == 0, return rc, "pivot %{public}s failed, err %{public}d", sandboxPackagePath.c_str(), errno); + + rc = umount2(".", MNT_DETACH); + APPSPAWN_CHECK(rc == 0, return rc, "MNT_DETACH failed, packagename is %{public}s", bundleName.c_str()); +#endif + return 0; +} + +int32_t SandboxCore::ChangeCurrentDir(std::string &sandboxPackagePath, const std::string &bundleName, + bool sandboxSharedStatus) +{ + int32_t ret = 0; + ret = chdir(sandboxPackagePath.c_str()); + APPSPAWN_CHECK(ret == 0, return ret, "chdir %{public}s failed, err %{public}d", sandboxPackagePath.c_str(), errno); + + if (sandboxSharedStatus) { + ret = chroot(sandboxPackagePath.c_str()); + APPSPAWN_CHECK(ret == 0, return ret, "chroot %{public}s failed, err %{public}d", + sandboxPackagePath.c_str(), errno); + return ret; + } + + ret = syscall(SYS_pivot_root, sandboxPackagePath.c_str(), sandboxPackagePath.c_str()); + APPSPAWN_CHECK(ret == 0, return ret, "pivot %{public}s failed, err %{public}d", sandboxPackagePath.c_str(), errno); + + ret = umount2(".", MNT_DETACH); + APPSPAWN_CHECK(ret == 0, return ret, "MNT_DETACH failed, packagename is %{public}s", bundleName.c_str()); + return ret; +} + + + +static const DecDenyPathTemplate DEC_DENY_PATH_MAP[] = { + {"ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY", "/storage/Users/currentUser/Download"}, + {"ohos.permission.READ_WRITE_DESKTOP_DIRECTORY", "/storage/Users/currentUser/Desktop"}, + {"ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY", "/storage/Users/currentUser/Documents"}, +}; + +int32_t SandboxCore::SetDecWithDir(const AppSpawningCtx *appProperty, uint32_t userId) +{ + AppSpawnMsgAccessToken *tokenInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_ACCESS_TOKEN_INFO)); + APPSPAWN_CHECK(tokenInfo != nullptr, return APPSPAWN_MSG_INVALID, "Get token id failed."); + + AppSpawnMsgBundleInfo *bundleInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + APPSPAWN_CHECK(bundleInfo != nullptr, return APPSPAWN_MSG_INVALID, "No bundle info in msg %{public}s", + GetBundleName(appProperty)); + + uint32_t flags = CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_ATOMIC_SERVICE) ? 0x4 : 0; + if (flags == 0) { + flags = (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_CLONE_ENABLE) && + bundleInfo->bundleIndex > 0) ? 0x1 : 0; + } + std::ostringstream clonePackageName; + if (flags == 1) { + clonePackageName << "+clone-" << bundleInfo->bundleIndex << "+" << bundleInfo->bundleName; + } else { + clonePackageName << bundleInfo->bundleName; + } + std::string dir = "/storage/Users/currentUser/Download/" + clonePackageName.str(); + DecPolicyInfo decPolicyInfo = {0}; + decPolicyInfo.pathNum = 1; + PathInfo pathInfo = {0}; + pathInfo.path = strdup(dir.c_str()); + if (pathInfo.path == nullptr) { + APPSPAWN_LOGE("strdup %{public}s failed, err %{public}d", dir.c_str(), errno); + return APPSPAWN_MSG_INVALID; + } + pathInfo.pathLen = static_cast(strlen(pathInfo.path)); + pathInfo.mode = SANDBOX_MODE_WRITE | SANDBOX_MODE_READ; + decPolicyInfo.path[0] = pathInfo; + decPolicyInfo.tokenId = tokenInfo->accessTokenIdEx; + decPolicyInfo.flag = true; + SetDecPolicyInfos(&decPolicyInfo); + + if (decPolicyInfo.path[0].path) { + free(decPolicyInfo.path[0].path); + decPolicyInfo.path[0].path = nullptr; + } + return 0; +} + +int32_t SandboxCore::SetDecPolicyWithPermission(const AppSpawningCtx *appProperty, SandboxMountConfig &mountConfig) +{ + if (mountConfig.decPaths.size() == 0) { + return 0; + } + AppSpawnMsgAccessToken *tokenInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_ACCESS_TOKEN_INFO)); + APPSPAWN_CHECK(tokenInfo != nullptr, return APPSPAWN_MSG_INVALID, "Get token id failed."); + + DecPolicyInfo decPolicyInfo = {0}; + decPolicyInfo.pathNum = mountConfig.decPaths.size(); + int ret = 0; + for (uint32_t i = 0; i < decPolicyInfo.pathNum; i++) { + PathInfo pathInfo = {0}; + pathInfo.path = strdup(mountConfig.decPaths[i].c_str()); + if (pathInfo.path == nullptr) { + APPSPAWN_LOGE("strdup %{public}s failed, err %{public}d", mountConfig.decPaths[i].c_str(), errno); + ret = APPSPAWN_ERROR_UTILS_MEM_FAIL; + goto EXIT; + } + pathInfo.pathLen = static_cast(strlen(pathInfo.path)); + pathInfo.mode = SANDBOX_MODE_WRITE | SANDBOX_MODE_READ; + decPolicyInfo.path[i] = pathInfo; + } + decPolicyInfo.tokenId = tokenInfo->accessTokenIdEx; + decPolicyInfo.flag = true; + SetDecPolicyInfos(&decPolicyInfo); +EXIT: + for (uint32_t i = 0; i < decPolicyInfo.pathNum; i++) { + if (decPolicyInfo.path[i].path) { + free(decPolicyInfo.path[i].path); + decPolicyInfo.path[i].path = nullptr; + } + } + return ret; +} + +void SandboxCore::SetDecDenyWithDir(const AppSpawningCtx *appProperty) +{ + int32_t userFileIndex = GetPermissionIndex(nullptr, SandboxCommonDef::READ_WRITE_USER_FILE_MODE.c_str()); + if (CheckAppPermissionFlagSet(appProperty, static_cast(userFileIndex)) == 0) { + APPSPAWN_LOGV("The app doesn't have %{public}s, no need to set deny rules", + SandboxCommonDef::READ_WRITE_USER_FILE_MODE.c_str()); + return; + } + + AppSpawnMsgAccessToken *tokenInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_ACCESS_TOKEN_INFO)); + APPSPAWN_CHECK(tokenInfo != nullptr, return, "Get token id failed"); + + DecPolicyInfo decPolicyInfo = {0}; + decPolicyInfo.pathNum = 0; + uint32_t count = ARRAY_LENGTH(DEC_DENY_PATH_MAP); + for (uint32_t i = 0, j = 0; i < count; i++) { + int32_t index = GetPermissionIndex(nullptr, DEC_DENY_PATH_MAP[i].permission); + if (CheckAppPermissionFlagSet(appProperty, static_cast(index))) { + continue; + } + PathInfo pathInfo = {0}; + pathInfo.path = const_cast(DEC_DENY_PATH_MAP[i].decPath); + pathInfo.pathLen = static_cast(strlen(pathInfo.path)); + pathInfo.mode = DEC_MODE_DENY_READ | DEC_MODE_DENY_WRITE; + decPolicyInfo.path[j++] = pathInfo; + decPolicyInfo.pathNum += 1; + } + decPolicyInfo.tokenId = tokenInfo->accessTokenIdEx; + decPolicyInfo.flag = true; + SetDecPolicyInfos(&decPolicyInfo); +} + +std::string SandboxCore::ConvertDebugRealPath(const AppSpawningCtx *appProperty, std::string path) +{ + AppSpawnMsgBundleInfo *info = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (info == nullptr || dacInfo == nullptr) { + return ""; + } + if (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_ATOMIC_SERVICE)) { + path = SandboxCommon::ReplaceAllVariables(path, SandboxCommonDef::g_variablePackageName, info->bundleName); + } + return SandboxCommon::ConvertToRealPath(appProperty, path); +} + +void SandboxCore::DoUninstallDebugSandbox(std::vector &bundleList, cJSON *config) +{ + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(config, SandboxCommonDef::g_mountPrefix); + if (mountPoints == nullptr || !cJSON_IsArray(mountPoints)) { + APPSPAWN_LOGI("Invalid mountPoints"); + return; + } + + auto processor = [&bundleList](cJSON *mntPoint) { + const char *srcPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_srcPath); + const char *sandboxPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_sandBoxPath); + if (srcPathChr == nullptr || sandboxPathChr == nullptr) { + return 0; + } + std::string sandboxPath(sandboxPathChr); + for (const auto& currentBundle : bundleList) { + sandboxPath = currentBundle + sandboxPath; + APPSPAWN_LOGV("DoUninstallDebugSandbox with path %{public}s", sandboxPath.c_str()); + APPSPAWN_CHECK(access(sandboxPath.c_str(), F_OK) == 0, return 0, + "Invalid path %{public}s", sandboxPath.c_str()); + int ret = umount2(sandboxPath.c_str(), MNT_DETACH); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "umount failed %{public}d %{public}d", ret, errno); + ret = rmdir(sandboxPath.c_str()); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "rmdir failed %{public}d %{public}d", ret, errno); + } + return 0; + }; + + (void)SandboxCommon::HandleArrayForeach(mountPoints, processor); +} + +int32_t SandboxCore::GetPackageList(AppSpawningCtx *property, std::vector &bundleList, bool tmp) +{ + APPSPAWN_CHECK(property != nullptr, return APPSPAWN_ARG_INVALID, "Invalid property"); + AppDacInfo *info = reinterpret_cast(GetAppProperty(property, TLV_DAC_INFO)); + if (GetBundleName(property) == nullptr ||SandboxCommon::CheckBundleName(GetBundleName(property)) != 0 || + info == nullptr) { + std::string uid; + char *userId = (char *)GetAppSpawnMsgExtInfo(property->message, MSG_EXT_NAME_USERID, nullptr); + if (userId != nullptr) { + uid = std::string(userId); + } else { + APPSPAWN_CHECK(info != nullptr, return APPSPAWN_ARG_INVALID, "Invalid dacInfo"); + uid = std::to_string(info->uid / UID_BASE); + } + std::string defaultSandboxRoot = (tmp ? SandboxCommonDef::g_mntTmpRoot : SandboxCommonDef::g_mntShareRoot) + + uid + "/debug_hap"; + APPSPAWN_CHECK(access(defaultSandboxRoot.c_str(), F_OK) == 0, return APPSPAWN_ARG_INVALID, + "Failed to access %{public}s, err %{public}d", defaultSandboxRoot.c_str(), errno); + + DIR *dir = opendir(defaultSandboxRoot.c_str()); + if (dir == nullptr) { + APPSPAWN_LOGE("Failed to open %{public}s, err %{public}d", defaultSandboxRoot.c_str(), errno); + return APPSPAWN_SYSTEM_ERROR; + } + struct dirent *entry; + while ((entry = readdir(dir)) != nullptr) { + if (entry->d_name[0] == '.') { + continue; + } + std::string packagePath = defaultSandboxRoot + "/" + std::string(entry->d_name); + APPSPAWN_LOGV("GetPackageList %{public}s", packagePath.c_str()); + bundleList.push_back(packagePath); + } + closedir(dir); + } else { + bundleList.push_back(ConvertDebugRealPath(property, tmp ? SandboxCommonDef::g_mntTmpSandboxRoot : + SandboxCommonDef::g_mntShareSandboxRoot)); + } + return 0; +} + +int32_t SandboxCore::UninstallDebugSandbox(AppSpawnMgr *content, AppSpawningCtx *property) +{ + APPSPAWN_CHECK(property != nullptr && content != nullptr, return APPSPAWN_ARG_INVALID, "Invalid property"); + + std::vector bundleList; + int ret = GetPackageList(property, bundleList, true); + APPSPAWN_CHECK(ret == 0, return -1, "GetPackageList failed"); + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(property, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANBOX_APP_JSON_CONFIG; + for (auto& wholeConfig : SandboxCommon::GetCJsonConfig(type)) { + cJSON *debugJson = GetFirstCommonConfig(wholeConfig, SandboxCommonDef::g_debughap); + if (!debugJson) { + continue; + } + cJSON *debugCommonConfig = GetFirstSubConfig(debugJson, SandboxCommonDef::g_commonPrefix); + if (!debugCommonConfig) { + continue; + } + DoUninstallDebugSandbox(bundleList, debugCommonConfig); + + cJSON *debugPermissionConfig = GetFirstSubConfig(debugJson, SandboxCommonDef::g_permissionPrefix); + if (!debugPermissionConfig) { + continue; + } + + cJSON *permissionChild = debugPermissionConfig->child; + while (permissionChild != nullptr) { + DoUninstallDebugSandbox(bundleList, permissionChild); + permissionChild = permissionChild->next; + } + } + bundleList.clear(); + ret = GetPackageList(property, bundleList, false); + APPSPAWN_CHECK(ret == 0, return -1, "GetPackageList failed"); + for (const auto& currentBundle : bundleList) { + std::string sandboxPath = currentBundle; + APPSPAWN_LOGV("UninstallDebugSandbox with path %{public}s", sandboxPath.c_str()); + APPSPAWN_CHECK(access(sandboxPath.c_str(), F_OK) == 0, continue, + "Invalid path %{public}s", sandboxPath.c_str()); + ret = umount2(sandboxPath.c_str(), MNT_DETACH); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "umount failed %{public}d %{public}d", ret, errno); + ret = rmdir(sandboxPath.c_str()); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "rmdir failed %{public}d %{public}d", ret, errno); + } + + return 0; +} + +int32_t SandboxCore::DoMountDebugPoints(const AppSpawningCtx *appProperty, cJSON *appConfig) +{ + std::string bundleName = GetBundleName(appProperty); + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(appConfig, SandboxCommonDef::g_mountPrefix); + if (mountPoints == nullptr || !cJSON_IsArray(mountPoints)) { + APPSPAWN_LOGI("mount config is not found, app name is %{public}s", bundleName.c_str()); + return 0; + } + + std::string sandboxRoot = ConvertDebugRealPath(appProperty, SandboxCommonDef::g_mntTmpSandboxRoot); + int atomicService = CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_ATOMIC_SERVICE); + + auto processor = [&sandboxRoot, &atomicService, &appProperty](cJSON *mntPoint) { + const char *srcPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_srcPath); + const char *sandboxPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_sandBoxPath); + if (srcPathChr == nullptr || sandboxPathChr == nullptr) { + return 0; + } + std::string srcPath(srcPathChr); + std::string sandboxPath(sandboxPathChr); + srcPath = SandboxCommon::ConvertToRealPath(appProperty, srcPath); + sandboxPath = GetSandboxPath(appProperty, mntPoint, SandboxCommonDef::g_debughap, sandboxRoot); + if (access(sandboxPath.c_str(), F_OK) == 0) { + APPSPAWN_CHECK(atomicService, return 0, "sandbox path already exist"); + APPSPAWN_CHECK(umount2(sandboxPath.c_str(), MNT_DETACH) == 0, return 0, + "umount sandbox path failed, errno is %{public}d %{public}s", errno, sandboxPath.c_str()); + } + SandboxMountConfig mountConfig = {0}; + SandboxCommon::GetSandboxMountConfig(appProperty, SandboxCommonDef::g_debughap, mntPoint, mountConfig); + SharedMountArgs arg = { + .srcPath = srcPath.c_str(), + .destPath = sandboxPath.c_str(), + .fsType = mountConfig.fsType.c_str(), + .mountFlags = SandboxCommon::GetMountFlags(mntPoint), + .options = mountConfig.optionsPoint.c_str(), + .mountSharedFlag = + GetBoolValueFromJsonObj(mntPoint, SandboxCommonDef::g_mountSharedFlag, false) ? MS_SHARED : MS_SLAVE + }; + int ret = SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); + APPSPAWN_CHECK(ret == 0 || !SandboxCommon::IsMountSuccessful(mntPoint), return ret, + "DoMountDebugPoints %{public}s failed", arg.destPath); + return ret; + }; + + (void)SandboxCommon::HandleArrayForeach(mountPoints, processor); + return 0; +} + +int32_t SandboxCore::MountDebugSharefs(const AppSpawningCtx *property, const char *src, const char *target) +{ + char dataPath[SandboxCommonDef::OPTIONS_MAX_LEN] = {0}; + int ret = snprintf_s(dataPath, SandboxCommonDef::OPTIONS_MAX_LEN, SandboxCommonDef::OPTIONS_MAX_LEN - 1, + "%s/data", target); + if (ret >= 0 && access(dataPath, F_OK) == 0) { + return 0; + } + + ret = MakeDirRec(target, SandboxCommonDef::FILE_MODE, 1); + if (ret != 0) { + return APPSPAWN_SANDBOX_ERROR_MKDIR_FAIL; + } + + AppDacInfo *info = reinterpret_cast(GetAppProperty(property, TLV_DAC_INFO)); + if (info == nullptr) { + return APPSPAWN_ARG_INVALID; + } + char options[SandboxCommonDef::OPTIONS_MAX_LEN] = {0}; + ret = snprintf_s(options, SandboxCommonDef::OPTIONS_MAX_LEN, SandboxCommonDef::OPTIONS_MAX_LEN - 1, + "override_support_delete,user_id=%u", info->uid / UID_BASE); + if (ret <= 0) { + return APPSPAWN_ERROR_UTILS_MEM_FAIL; + } + + if (mount(src, target, "sharefs", MS_NODEV, options) != 0) { + APPSPAWN_LOGE("sharefs mount %{public}s to %{public}s failed, errno %{public}d", src, target, errno); + return APPSPAWN_SANDBOX_ERROR_MOUNT_FAIL; + } + if (mount(nullptr, target, nullptr, MS_SHARED, nullptr) != 0) { + APPSPAWN_LOGE("mount path %{public}s to shared failed, errno %{public}d", target, errno); + return APPSPAWN_SANDBOX_ERROR_MOUNT_FAIL; + } + + return 0; +} + +int32_t SandboxCore::InstallDebugSandbox(AppSpawnMgr *content, AppSpawningCtx *property) +{ + if (!IsDeveloperModeOn(property)) { + return 0; + } + + uint32_t len = 0; + char *provisionType = reinterpret_cast(GetAppPropertyExt(property, + MSG_EXT_NAME_PROVISION_TYPE, &len)); + if (provisionType == nullptr || len == 0 || strcmp(provisionType, "debug") != 0) { + return 0; + } + + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(property, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANBOX_APP_JSON_CONFIG; + + for (auto& wholeConfig : SandboxCommon::GetCJsonConfig(type)) { + cJSON *debugJson = GetFirstCommonConfig(wholeConfig, SandboxCommonDef::g_debughap); + if (!debugJson) { + continue; + } + cJSON *debugCommonConfig = GetFirstSubConfig(debugJson, SandboxCommonDef::g_commonPrefix); + if (!debugCommonConfig) { + continue; + } + DoMountDebugPoints(property, debugCommonConfig); + + cJSON *debugPermissionConfig = GetFirstSubConfig(debugJson, SandboxCommonDef::g_permissionPrefix); + if (!debugPermissionConfig) { + continue; + } + + cJSON *permissionChild = debugPermissionConfig->child; + while (permissionChild != nullptr) { + int index = GetPermissionIndex(nullptr, permissionChild->string); + if (CheckAppPermissionFlagSet(property, static_cast(index)) == 0) { + permissionChild = permissionChild->next; + continue; + } + cJSON *permissionMountPaths = cJSON_GetArrayItem(permissionChild, 0); + if (!permissionMountPaths) { + permissionChild = permissionChild->next; + continue; + } + DoMountDebugPoints(property, permissionMountPaths); + + permissionChild = permissionChild->next; + } + } + + MountDebugSharefs(property, ConvertDebugRealPath(property, SandboxCommonDef::g_mntTmpSandboxRoot).c_str(), + ConvertDebugRealPath(property, SandboxCommonDef::g_mntShareSandboxRoot).c_str()); + return 0; +} +} // namespace AppSpawn +} // namespace OHOS diff --git a/modules/sandbox/normal/sandbox_core.h b/modules/sandbox/normal/sandbox_core.h new file mode 100644 index 00000000..f91e452e --- /dev/null +++ b/modules/sandbox/normal/sandbox_core.h @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SANDBOX_MANAGER_H +#define SANDBOX_MANAGER_H + +#include +#include +#include +#include "sandbox_def.h" +#include "appspawn_msg.h" +#include "appspawn_server.h" +#include "appspawn_manager.h" +#include "sandbox_shared_mount.h" +#include "sandbox_common.h" + +namespace OHOS { +namespace AppSpawn { + +class SandboxCore { +public: + // 沙箱挂载公共处理 + static int32_t DoAllMntPointsMount(const AppSpawningCtx *appProperty, cJSON *appConfig, + const char *typeName, const std::string §ion = "app-base"); + static int32_t DoAddGid(AppSpawningCtx *appProperty, cJSON *appConfig, + const char* permissionName, const std::string §ion); + static int32_t DoAllSymlinkPointslink(const AppSpawningCtx *appProperty, cJSON *appConfig); + static int32_t DoSandboxRootFolderCreate(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); + static int32_t DoSandboxRootFolderCreateAdapt(std::string &sandboxPackagePath); + static int32_t HandleFlagsPoint(const AppSpawningCtx *appProperty, cJSON *appConfig); + static int32_t SetOverlayAppSandboxProperty(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); + static int32_t SetBundleResourceAppSandboxProperty(const AppSpawningCtx *appProperty, + std::string &sandboxPackagePath); + static bool NeedNetworkIsolated(AppSpawningCtx *property); + + // 处理应用沙箱挂载 + static int32_t SetCommonAppSandboxProperty(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); + static int32_t SetPrivateAppSandboxProperty(const AppSpawningCtx *appProperty); + static int32_t SetPermissionAppSandboxProperty(AppSpawningCtx *appProperty); + static int32_t SetSandboxProperty(AppSpawningCtx *appProperty, std::string &sandboxPackagePath); + static int32_t SetAppSandboxProperty(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags = CLONE_NEWNS); + + static int32_t SetRenderSandboxPropertyNweb(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); + static int32_t SetAppSandboxPropertyNweb(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags = CLONE_NEWNS); + + // 沙箱目录切根 + static int32_t ChangeCurrentDir(std::string &sandboxPackagePath, const std::string &bundleName, + bool sandboxSharedStatus); + + // 设置DEC规则 + static int32_t SetDecWithDir(const AppSpawningCtx *appProperty, uint32_t userId); + static int32_t SetDecPolicyWithPermission(const AppSpawningCtx *appProperty, SandboxMountConfig &mountConfig); + static void SetDecDenyWithDir(const AppSpawningCtx *appProperty); + + // debug hap + static int32_t UninstallDebugSandbox(AppSpawnMgr *content, AppSpawningCtx *property); + static int32_t InstallDebugSandbox(AppSpawnMgr *content, AppSpawningCtx *property); + +private: + // 获取应用信息 + static int EnableSandboxNamespace(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags); + static uint32_t GetAppMsgFlags(const AppSpawningCtx *property); + static bool CheckMountFlag(const AppSpawningCtx *appProperty, const std::string bundleName, + cJSON *appConfig); + static void UpdateMsgFlagsWithPermission(AppSpawningCtx *appProperty); + static int32_t UpdatePermissionFlags(AppSpawningCtx *appProperty); + static std::string GetSandboxPath(const AppSpawningCtx *appProperty, cJSON *mntPoint, + const std::string §ion, std::string sandboxRoot); + + // 解析挂载信息公共函数 + static cJSON *GetFirstCommonConfig(cJSON *wholeConfig, const char *prefix); + static cJSON *GetFirstSubConfig(cJSON *parent, const char *key); + + // 处理dlpmanager挂载 + static int32_t DoDlpAppMountStrategy(const AppSpawningCtx *appProperty, const std::string &srcPath, + const std::string &sandboxPath, const std::string &fsType, unsigned long mountFlags); + static int32_t HandleSpecialAppMount(const AppSpawningCtx *appProperty, const std::string &srcPath, + const std::string &sandboxPath, const std::string &fsType, unsigned long mountFlags); + + // 处理应用私有挂载 + static cJSON *GetPrivateJsonInfo(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t DoSandboxFilePrivateBind(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t DoSandboxFilePrivateSymlink(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t DoSandboxFilePrivateFlagsPointHandle(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t SetPrivateAppSandboxProperty_(const AppSpawningCtx *appProperty, cJSON *config); + + // 处理应用基于权限挂载 + static int32_t DoSandboxFilePermissionBind(AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t SetPermissionAppSandboxProperty_(AppSpawningCtx *appProperty, cJSON *config); + + // 处理应用公共挂载 + static int32_t DoSandboxFileCommonBind(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t DoSandboxFileCommonSymlink(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t DoSandboxFileCommonFlagsPointHandle(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t SetCommonAppSandboxProperty_(const AppSpawningCtx *appProperty, cJSON *config); + + // 处理可变参数的挂载 + static int32_t MountAllHsp(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); + static int32_t MountAllGroup(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); + + // 沙箱回调函数 + static int32_t ProcessMountPoint(cJSON *mntPoint, MountPointProcessParams ¶ms); + + // debug hap + static std::string ConvertDebugRealPath(const AppSpawningCtx *appProperty, std::string path); + static void DoUninstallDebugSandbox(std::vector &bundleList, cJSON *mountPoints); + static int32_t GetPackageList(AppSpawningCtx *property, std::vector &bundleList, bool tmp); + + static int32_t DoMountDebugPoints(const AppSpawningCtx *appProperty, cJSON *appConfig); + static int32_t MountDebugSharefs(const AppSpawningCtx *property, const char *src, const char *target); +}; + +} // namespace AppSpawn +} // namespace OHOS + +#endif // SANDBOX_MANAGER_H diff --git a/modules/sandbox/normal/sandbox_def.h b/modules/sandbox/normal/sandbox_def.h new file mode 100644 index 00000000..f3ddb728 --- /dev/null +++ b/modules/sandbox/normal/sandbox_def.h @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SANDBOX_DEF_H +#define SANDBOX_DEF_H + +#include +#include +#include +#include + +namespace OHOS { +namespace AppSpawn { +namespace SandboxCommonDef { +// 全局常量定义 +constexpr int32_t OPTIONS_MAX_LEN = 256; +constexpr int32_t FILE_ACCESS_COMMON_DIR_STATUS = 0; +constexpr int32_t FILE_CROSS_APP_STATUS = 1; +constexpr static mode_t FILE_MODE = 0711; +constexpr static mode_t BASIC_MOUNT_FLAGS = MS_REC | MS_BIND; +constexpr int32_t MAX_MOUNT_TIME = 500; // 500us +constexpr int32_t LOCK_STATUS_SIZE = 16; + +// 沙盒配置文件 +const std::string APP_JSON_CONFIG = "/appdata-sandbox.json"; +const std::string APP_ISOLATED_JSON_CONFIG = "/appdata-sandbox-isolated.json"; + +/* 沙盒配置文件中关键字 */ +// 公共属性 +constexpr const char *g_sandboxRootPrefix = "sandbox-root"; +constexpr const char *g_sandBoxNsFlags = "sandbox-ns-flags"; +constexpr const char *g_topSandBoxSwitchPrefix = "top-sandbox-switch"; +constexpr const char *g_sandBoxSwitchPrefix = "sandbox-switch"; +const std::string g_ohosGpu = "__internal__.com.ohos.gpu"; +const std::string g_ohosRender = "__internal__.com.ohos.render"; +constexpr const char *g_commonPrefix = "common"; +constexpr const char *g_privatePrefix = "individual"; +constexpr const char *g_permissionPrefix = "permission"; +constexpr const char *g_appBase = "app-base"; +constexpr const char *g_appResources = "app-resources"; +constexpr const char *g_flagePoint = "flags-point"; +const std::string g_internal = "__internal__"; +const std::string g_mntTmpRoot = "/mnt/debugtmp/"; +const std::string g_mntShareRoot = "/mnt/debug/"; +const std::string g_sandboxRootPathTemplate = "/mnt/sandbox//"; +const std::string g_originSandboxPath = "/mnt/sandbox/"; + +// 挂载目录字段 +constexpr const char *g_mountPrefix = "mount-paths"; +constexpr const char *g_srcPath = "src-path"; +constexpr const char *g_sandBoxPath = "sandbox-path"; +constexpr const char *g_sandBoxFlags = "sandbox-flags"; +constexpr const char *g_fsType = "fs-type"; +constexpr const char *g_sandBoxOptions = "options"; +constexpr const char *g_actionStatuc = "check-action-status"; +constexpr const char *g_destMode = "dest-mode"; +constexpr const char *g_flags = "flags"; + +// 挂载可选属性 +constexpr const char *g_sandBoxShared = "sandbox-shared"; +constexpr const char *g_mountSharedFlag = "mount-shared-flag"; +constexpr const char *g_dacOverrideSensitive = "dac-override-sensitive"; +constexpr const char *g_sandBoxFlagsCustomized = "sandbox-flags-customized"; +constexpr const char *g_appAplName = "app-apl-name"; +constexpr const char *g_sandBoxDecPath = "dec-paths"; +constexpr const char *CREATE_SANDBOX_PATH = "create-sandbox-path"; + +// link目录字段 +constexpr const char *g_symlinkPrefix = "symbol-links"; +constexpr const char *g_targetName = "target-name"; +constexpr const char *g_linkName = "link-name"; + +constexpr const char *g_gidPrefix = "gids"; + +// 可变参数 +const std::string g_userId = ""; +const std::string g_permissionUser = ""; +const std::string g_packageName = ""; +const std::string g_packageNameIndex = ""; +const std::string g_variablePackageName = ""; +const std::string g_clonePackageName = ""; +const std::string g_arkWebPackageName = ""; +const std::string g_hostUserId = ""; + +/* HSP */ +const std::string HSPLIST_SOCKET_TYPE = "HspList"; +const std::string g_hspList_key_bundles = "bundles"; +const std::string g_hspList_key_modules = "modules"; +const std::string g_hspList_key_versions = "versions"; +const std::string g_sandboxHspInstallPath = "/data/storage/el1/bundle/"; + +/* DataGroup */ +const std::string DATA_GROUP_SOCKET_TYPE = "DataGroup"; +const std::string g_groupList_key_dataGroupId = "dataGroupId"; +const std::string g_groupList_key_gid = "gid"; +const std::string g_groupList_key_dir = "dir"; +const std::string g_groupList_key_uuid = "uuid"; + +/* Overlay */ +const std::string OVERLAY_SOCKET_TYPE = "Overlay"; +const std::string g_overlayPath = "/data/storage/overlay/"; + +/* system hap */ +const std::string APL_SYSTEM_CORE = "system_core"; +const std::string APL_SYSTEM_BASIC = "system_basic"; +const std::string g_physicalAppInstallPath = "/data/app/el1/bundle/public/"; +const std::string g_dataBundles = "/data/bundles/"; + +/* bundle resource with APP_FLAGS_BUNDLE_RESOURCES */ +const std::string g_bundleResourceSrcPath = "/data/service/el1/public/bms/bundle_resources/"; +const std::string g_bundleResourceDestPath = "/data/storage/bundle_resources/"; + +/* 配置文件中value校验值 */ +const std::string g_sandBoxRootDir = "/mnt/sandbox/"; +const std::string g_sandBoxRootDirNweb = "/mnt/sandbox/com.ohos.render/"; +const std::string DEV_SHM_DIR = "/dev/shm/"; +const std::string g_statusCheck = "true"; +const std::string g_sbxSwitchCheck = "ON"; +const std::string g_dlpBundleName = "com.ohos.dlpmanager"; + +/* debug hap */ +constexpr const char *g_mntTmpSandboxRoot = "/mnt/debugtmp//debug_hap/"; +constexpr const char *g_mntShareSandboxRoot = "/mnt/debug//debug_hap/"; +constexpr const char *g_debughap = "debug"; + +/* 分割符 */ +constexpr const char *g_fileSeparator = "/"; +constexpr const char *g_overlayDecollator = "|"; + +/* 权限名 */ +const std::string FILE_CROSS_APP_MODE = "ohos.permission.FILE_CROSS_APP"; +const std::string FILE_ACCESS_COMMON_DIR_MODE = "ohos.permission.FILE_ACCESS_COMMON_DIR"; +const std::string ACCESS_DLP_FILE_MODE = "ohos.permission.ACCESS_DLP_FILE"; +const std::string FILE_ACCESS_MANAGER_MODE = "ohos.permission.FILE_ACCESS_MANAGER"; +const std::string READ_WRITE_USER_FILE_MODE = "ohos.permission.READ_WRITE_USER_FILE"; +const std::string GET_ALL_PROCESSES_MODE = "ohos.permission.GET_ALL_PROCESSES"; +const std::string ARK_WEB_PERSIST_PACKAGE_NAME = "persist.arkwebcore.package_name"; + +// 枚举类型 +enum SandboxConfigType { + SANBOX_APP_JSON_CONFIG, + SANBOX_ISOLATED_JSON_CONFIG +}; + +} // namespace SandboxCommonDef +} // namespace AppSpawn +} // namespace OHOS + +#endif // SANDBOX_DEF_H \ No newline at end of file diff --git a/modules/sandbox/sandbox_shared_mount.cpp b/modules/sandbox/normal/sandbox_shared_mount.cpp similarity index 90% rename from modules/sandbox/sandbox_shared_mount.cpp rename to modules/sandbox/normal/sandbox_shared_mount.cpp index 528dca99..43fa91a3 100644 --- a/modules/sandbox/sandbox_shared_mount.cpp +++ b/modules/sandbox/normal/sandbox_shared_mount.cpp @@ -86,13 +86,18 @@ const DataGroupSandboxPathTemplate *GetDataGroupArgTemplate(uint32_t category) return nullptr; } -bool IsValidDataGroupItem(nlohmann::json &item) +bool IsValidDataGroupItem(cJSON *item) { // Check if the item contains the specified key and if the value corresponding to the key is a string - if (item.contains(GROUPLIST_KEY_DATAGROUPID) && item[GROUPLIST_KEY_DATAGROUPID].is_string() && - item.contains(GROUPLIST_KEY_GID) && item[GROUPLIST_KEY_GID].is_string() && - item.contains(GROUPLIST_KEY_DIR) && item[GROUPLIST_KEY_DIR].is_string() && - item.contains(GROUPLIST_KEY_UUID) && item[GROUPLIST_KEY_UUID].is_string()) { + cJSON *datagroupId = cJSON_GetObjectItem(item, GROUPLIST_KEY_DATAGROUPID); + cJSON *gid = cJSON_GetObjectItem(item, GROUPLIST_KEY_GID); + cJSON *dir = cJSON_GetObjectItem(item, GROUPLIST_KEY_DIR); + cJSON *uuid = cJSON_GetObjectItem(item, GROUPLIST_KEY_UUID); + + if (datagroupId && cJSON_IsString(datagroupId) && + gid && cJSON_IsString(gid) && + dir && cJSON_IsString(dir) && + uuid && cJSON_IsString(uuid)) { return true; } return false; @@ -437,16 +442,6 @@ static int AddDataGroupItemToQueue(AppSpawnMgr *content, const std::string &srcP return 0; } -static std::string GetExtraInfoByType(const AppSpawningCtx *appPropery, const std::string &type) -{ - uint32_t len = 0; - char *info = reinterpret_cast(GetAppPropertyExt(appPropery, type.c_str(), &len)); - if (info == nullptr) { - return ""; - } - return std::string(info, len); -} - static void DumpDataGroupCtxQueue(const ListNode *front) { if (front == nullptr) { @@ -466,33 +461,51 @@ static void DumpDataGroupCtxQueue(const ListNode *front) } } +static inline cJSON *GetJsonObjFromExtInfo(const AppSpawningCtx *property, const char *name) +{ + uint32_t size = 0; + char *extInfo = (char *)(GetAppSpawnMsgExtInfo(property->message, name, &size)); + if (size == 0 || extInfo == NULL) { + return NULL; + } + APPSPAWN_LOGV("Get json name %{public}s value %{public}s", name, extInfo); + cJSON *extInfoJson = cJSON_Parse(extInfo); // need to free + APPSPAWN_CHECK(extInfoJson != NULL, return NULL, "Invalid ext info %{public}s for %{public}s", extInfo, name); + return extInfoJson; +} + static int ParseDataGroupList(AppSpawnMgr *content, const AppSpawningCtx *property, AppDacInfo *info, const char *varBundleName) { int ret = 0; - std::string dataGroupList = GetExtraInfoByType(property, DATA_GROUP_SOCKET_TYPE); - if (dataGroupList.length() == 0) { + cJSON *dataGroupList = GetJsonObjFromExtInfo(property, DATA_GROUP_SOCKET_TYPE); + if (dataGroupList == nullptr || !cJSON_IsArray(dataGroupList)) { APPSPAWN_LOGE("dataGroupList is empty"); return APPSPAWN_ARG_INVALID; } - nlohmann::json dataGroupJson = nlohmann::json::parse(dataGroupList.c_str(), nullptr, false); - if (dataGroupJson.is_discarded() && dataGroupJson.contains(GROUPLIST_KEY_DATAGROUPID) && - dataGroupJson.contains(GROUPLIST_KEY_GID) && dataGroupJson.contains(GROUPLIST_KEY_DIR) && - dataGroupJson.contains(GROUPLIST_KEY_UUID)) { - APPSPAWN_LOGE("dataGroupJson is discarded"); - return APPSPAWN_ARG_INVALID; - } - for (auto &item : dataGroupJson) { - APPSPAWN_CHECK(IsValidDataGroupItem(item), return -1, "Element is not a valid data group item"); - std::string srcPath = item[GROUPLIST_KEY_DIR]; - APPSPAWN_CHECK(!CheckPath(srcPath), return -1, "src path %{public}s is invalid", srcPath.c_str()); + // Iterate through the array (assuming groups is an array) + cJSON *item = nullptr; + cJSON_ArrayForEach(item, dataGroupList) { + // Check if the item is valid + APPSPAWN_CHECK((item != nullptr && IsValidDataGroupItem(item)), break, + "Element is not a valid data group item"); + + cJSON *dirItem = cJSON_GetObjectItemCaseSensitive(item, "dir"); + cJSON *uuidItem = cJSON_GetObjectItemCaseSensitive(item, "uuid"); + if (dirItem == nullptr || !cJSON_IsString(dirItem) || uuidItem == nullptr || !cJSON_IsString(uuidItem)) { + APPSPAWN_LOGE("Data group element is invalid"); + break; + } + + const char *srcPath = dirItem->valuestring; + APPSPAWN_CHECK(!CheckPath(srcPath), break, "src path %{public}s is invalid", srcPath); + + int elxValue = GetElxInfoFromDir(srcPath); + APPSPAWN_CHECK((elxValue >= EL2 && elxValue < ELX_MAX), break, "Get elx value failed"); - int elxValue = GetElxInfoFromDir(srcPath.c_str()); - APPSPAWN_CHECK((elxValue >= EL2 && elxValue < ELX_MAX), return -1, "Get elx value failed"); - const DataGroupSandboxPathTemplate *templateItem = GetDataGroupArgTemplate(elxValue); - APPSPAWN_CHECK(templateItem != nullptr, return -1, "Get data group arg template failed"); + APPSPAWN_CHECK(templateItem != nullptr, break, "Get data group arg template failed"); // If permission isn't null, need check permission flag if (templateItem->permission != nullptr) { @@ -502,18 +515,16 @@ static int ParseDataGroupList(AppSpawnMgr *content, const AppSpawningCtx *proper continue; } } - // sandboxPath: /mnt/sandbox///data/storage/el/group std::string sandboxPath = "/mnt/sandbox/" + std::to_string(info->uid / UID_BASE) + "/" + varBundleName + templateItem->sandboxPath; - ret = AddDataGroupItemToQueue(content, srcPath, sandboxPath, item[GROUPLIST_KEY_UUID]); - if (ret != 0) { + ret = AddDataGroupItemToQueue(content, srcPath, sandboxPath, uuidItem->valuestring); APPSPAWN_LOGE("Add datagroup item to dataGroupCtxQueue failed, el%{public}d", elxValue); OH_ListRemoveAll(&content->dataGroupCtxQueue, nullptr); - return -1; - } + break;; } + cJSON_Delete(dataGroupList); DumpDataGroupCtxQueue(&content->dataGroupCtxQueue); return ret; @@ -552,7 +563,7 @@ int UpdateDataGroupDirs(AppSpawnMgr *content) } node = node->next; } - OH_ListRemoveAll(&content->dataGroupCtxQueue, NULL); + OH_ListRemoveAll(&content->dataGroupCtxQueue, nullptr); return 0; } @@ -581,7 +592,7 @@ static void MountDirToShared(AppSpawnMgr *content, const AppSpawningCtx *propert AppDacInfo *info = reinterpret_cast(GetAppProperty(property, TLV_DAC_INFO)); std::string varBundleName = ReplaceVarBundleName(property); - if (info == NULL || varBundleName == "") { + if (info == nullptr || varBundleName == "") { APPSPAWN_LOGE("Invalid app dac info or varBundleName"); return; } diff --git a/modules/sandbox/sandbox_shared_mount.h b/modules/sandbox/normal/sandbox_shared_mount.h similarity index 96% rename from modules/sandbox/sandbox_shared_mount.h rename to modules/sandbox/normal/sandbox_shared_mount.h index 1a24f2cc..0a09a3eb 100644 --- a/modules/sandbox/sandbox_shared_mount.h +++ b/modules/sandbox/normal/sandbox_shared_mount.h @@ -23,6 +23,7 @@ #include "appspawn_manager.h" #include "appspawn_utils.h" #include "list.h" +#include "json_utils.h" #ifdef __cplusplus extern "C" { @@ -57,7 +58,7 @@ struct SharedMountArgs { mode_t mountSharedFlag = MS_SLAVE; }; -bool IsValidDataGroupItem(nlohmann::json &item); +bool IsValidDataGroupItem(cJSON *item); int GetElxInfoFromDir(const char *path); const DataGroupSandboxPathTemplate *GetDataGroupArgTemplate(uint32_t category); void *GetEl1BundleMountCount(void); diff --git a/modules/sandbox/sandbox_utils.cpp b/modules/sandbox/sandbox_utils.cpp index 5fcefbc8..75e2ea47 100644 --- a/modules/sandbox/sandbox_utils.cpp +++ b/modules/sandbox/sandbox_utils.cpp @@ -75,9 +75,7 @@ namespace { const std::string APP_JSON_CONFIG("/appdata-sandbox.json"); const std::string APP_ISOLATED_JSON_CONFIG("/appdata-sandbox-isolated.json"); const std::string g_physicalAppInstallPath = "/data/app/el1/bundle/public/"; - const std::string g_sandboxGroupPath = "/data/storage/el2/group/"; const std::string g_sandboxHspInstallPath = "/data/storage/el1/bundle/"; - const std::string g_sandBoxAppInstallPath = "/data/accounts/account_0/applications/"; const std::string g_bundleResourceSrcPath = "/data/service/el1/public/bms/bundle_resources/"; const std::string g_bundleResourceDestPath = "/data/storage/bundle_resources/"; const std::string g_dataBundles = "/data/bundles/"; @@ -88,7 +86,7 @@ namespace { const std::string g_clonePackageName = ""; const std::string g_arkWebPackageName = ""; const std::string g_hostUserId = ""; - const std::string g_sandBoxDir = "/mnt/sandbox/"; + const std::string g_sandBoxRootDir = "/mnt/sandbox/"; const std::string g_statusCheck = "true"; const std::string g_sbxSwitchCheck = "ON"; const std::string g_dlpBundleName = "com.ohos.dlpmanager"; @@ -708,7 +706,7 @@ std::string SandboxUtils::GetSbxPathByConfig(const AppSpawningCtx *appProperty, variablePackageName << "+clone-" << bundleInfo->bundleIndex << "+" << bundleInfo->bundleName; tmpBundlePath = variablePackageName.str(); } - const std::string variableSandboxRoot = g_sandBoxDir + to_string(dacInfo->uid / UID_BASE) + + const std::string variableSandboxRoot = g_sandBoxRootDir + to_string(dacInfo->uid / UID_BASE) + "/" + isolatedFlagText.c_str() + tmpBundlePath; if (config.find(g_sandboxRootPrefix) != config.end()) { sandboxRoot = config[g_sandboxRootPrefix].get(); diff --git a/test/unittest/app_spawn_standard_test/BUILD.gn b/test/unittest/app_spawn_standard_test/BUILD.gn index 15a882f5..c9167e81 100644 --- a/test/unittest/app_spawn_standard_test/BUILD.gn +++ b/test/unittest/app_spawn_standard_test/BUILD.gn @@ -104,15 +104,15 @@ ohos_unittest("AppSpawn_ut") { "${appspawn_path}/modules/common/appspawn_namespace.c", "${appspawn_path}/modules/common/appspawn_silk.c", "${appspawn_path}/modules/nweb_adapter/nwebspawn_adapter.cpp", - "${appspawn_path}/modules/sandbox/appspawn_mount_template.c", + "${appspawn_path}/modules/sandbox/modern/appspawn_mount_template.c", "${appspawn_path}/modules/sandbox/appspawn_permission.c", - "${appspawn_path}/modules/sandbox/appspawn_sandbox.c", - "${appspawn_path}/modules/sandbox/sandbox_adapter.cpp", - "${appspawn_path}/modules/sandbox/sandbox_cfgvar.c", + "${appspawn_path}/modules/sandbox/modern/appspawn_sandbox.c", + "${appspawn_path}/modules/sandbox/modern/sandbox_adapter.cpp", + "${appspawn_path}/modules/sandbox/modern/sandbox_cfgvar.c", "${appspawn_path}/modules/sandbox/sandbox_dec.c", - "${appspawn_path}/modules/sandbox/sandbox_expand.c", - "${appspawn_path}/modules/sandbox/sandbox_load.c", - "${appspawn_path}/modules/sandbox/sandbox_manager.c", + "${appspawn_path}/modules/sandbox/modern/sandbox_expand.c", + "${appspawn_path}/modules/sandbox/modern/sandbox_load.c", + "${appspawn_path}/modules/sandbox/modern/sandbox_manager.c", ] # add stub @@ -312,15 +312,15 @@ ohos_unittest("AppSpawn_coldrun_ut") { "${appspawn_path}/modules/common/appspawn_namespace.c", "${appspawn_path}/modules/common/appspawn_silk.c", "${appspawn_path}/modules/nweb_adapter/nwebspawn_adapter.cpp", - "${appspawn_path}/modules/sandbox/appspawn_mount_template.c", + "${appspawn_path}/modules/sandbox/modern/appspawn_mount_template.c", "${appspawn_path}/modules/sandbox/appspawn_permission.c", - "${appspawn_path}/modules/sandbox/appspawn_sandbox.c", - "${appspawn_path}/modules/sandbox/sandbox_adapter.cpp", - "${appspawn_path}/modules/sandbox/sandbox_cfgvar.c", + "${appspawn_path}/modules/sandbox/modern/appspawn_sandbox.c", + "${appspawn_path}/modules/sandbox/modern/sandbox_adapter.cpp", + "${appspawn_path}/modules/sandbox/modern/sandbox_cfgvar.c", "${appspawn_path}/modules/sandbox/sandbox_dec.c", - "${appspawn_path}/modules/sandbox/sandbox_expand.c", - "${appspawn_path}/modules/sandbox/sandbox_load.c", - "${appspawn_path}/modules/sandbox/sandbox_manager.c", + "${appspawn_path}/modules/sandbox/modern/sandbox_expand.c", + "${appspawn_path}/modules/sandbox/modern/sandbox_load.c", + "${appspawn_path}/modules/sandbox/modern/sandbox_manager.c", ] if (appspawn_use_encaps == true) { @@ -504,15 +504,15 @@ ohos_unittest("AppSpawn_common_ut") { "${appspawn_path}/modules/common/appspawn_namespace.c", "${appspawn_path}/modules/common/appspawn_silk.c", "${appspawn_path}/modules/nweb_adapter/nwebspawn_adapter.cpp", - "${appspawn_path}/modules/sandbox/appspawn_mount_template.c", + "${appspawn_path}/modules/sandbox/modern/appspawn_mount_template.c", "${appspawn_path}/modules/sandbox/appspawn_permission.c", - "${appspawn_path}/modules/sandbox/appspawn_sandbox.c", - "${appspawn_path}/modules/sandbox/sandbox_adapter.cpp", - "${appspawn_path}/modules/sandbox/sandbox_cfgvar.c", + "${appspawn_path}/modules/sandbox/modern/appspawn_sandbox.c", + "${appspawn_path}/modules/sandbox/modern/sandbox_adapter.cpp", + "${appspawn_path}/modules/sandbox/modern/sandbox_cfgvar.c", "${appspawn_path}/modules/sandbox/sandbox_dec.c", - "${appspawn_path}/modules/sandbox/sandbox_expand.c", - "${appspawn_path}/modules/sandbox/sandbox_load.c", - "${appspawn_path}/modules/sandbox/sandbox_manager.c", + "${appspawn_path}/modules/sandbox/modern/sandbox_expand.c", + "${appspawn_path}/modules/sandbox/modern/sandbox_load.c", + "${appspawn_path}/modules/sandbox/modern/sandbox_manager.c", ] # add stub -- Gitee