• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "dlp_permission_service.h"
17 #include <chrono>
18 #include "accesstoken_kit.h"
19 #include "access_token_adapter.h"
20 #include "account_adapt.h"
21 #include "app_mgr_client.h"
22 #include "bundle_manager_adapter.h"
23 #include "bundle_mgr_client.h"
24 #include "config_policy_utils.h"
25 #include "dlp_credential_client.h"
26 #include "dlp_credential.h"
27 #include "dlp_kv_data_storage.h"
28 #include "dlp_permission.h"
29 #include "dlp_permission_log.h"
30 #include "dlp_permission_serializer.h"
31 #include "dlp_policy_mgr_client.h"
32 #include "dlp_sandbox_change_callback_manager.h"
33 #include "dlp_sandbox_info.h"
34 #include "dlp_dfx_define.h"
35 #include "file_operator.h"
36 #include "hap_token_info.h"
37 #include "if_system_ability_manager.h"
38 #include "ipc_skeleton.h"
39 #include "iservice_registry.h"
40 #include "open_dlp_file_callback_manager.h"
41 #if defined(DLP_DEBUG_ENABLE) && DLP_DEBUG_ENABLE == 1
42 #include "parameter.h"
43 #endif
44 #include "parameters.h"
45 #include "param_wrapper.h"
46 #include "permission_policy.h"
47 #include "system_ability_definition.h"
48 #include "visit_record_file_manager.h"
49 #include "os_account_manager.h"
50 #include "permission_manager_adapter.h"
51 #include "alg_utils.h"
52 #include "dlp_feature_info.h"
53 
54 namespace OHOS {
55 namespace Security {
56 namespace DlpPermission {
57 using namespace Security::AccessToken;
58 using namespace OHOS::AppExecFwk;
59 namespace {
60 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, SECURITY_DOMAIN_DLP_PERMISSION, "DlpPermissionService" };
61 constexpr const int32_t EDM_UID = 3057;
62 constexpr const int32_t SA_ID_DLP_PERMISSION_SERVICE = 3521;
63 const std::string PERMISSION_ACCESS_DLP_FILE = "ohos.permission.ACCESS_DLP_FILE";
64 const std::string PERMISSION_ENTERPRISE_ACCESS_DLP_FILE = "ohos.permission.ENTERPRISE_ACCESS_DLP_FILE";
65 static const std::string ALLOW_ACTION[] = {"ohos.want.action.CREATE_FILE"};
66 static const std::string DLP_MANAGER = "com.ohos.dlpmanager";
67 static const std::chrono::seconds SLEEP_TIME(120);
68 static const int REPEAT_TIME = 5;
69 static const std::string DLP_CONFIG = "etc/dlp_permission/dlp_config.json";
70 static const std::string SUPPORT_FILE_TYPE = "support_file_type";
71 static const std::string DEAULT_DLP_CONFIG = "/system/etc/dlp_config.json";
72 static const std::string DLP_ENABLE = "const.dlp.dlp_enable";
73 static const std::string DEVELOPER_MODE = "const.security.developermode.state";
74 static const std::string TRUE_VALUE = "true";
75 static const std::string FALSE_VALUE = "false";
76 static const std::string SEPARATOR = "_";
77 static const std::string FOUNDATION_SERVICE_NAME = "foundation";
78 static const uint32_t MAX_SUPPORT_FILE_TYPE_NUM = 1024;
79 static const uint32_t MAX_RETENTION_SIZE = 1024;
80 static const uint32_t MAX_FILE_RECORD_SIZE = 1024;
81 static const uint32_t MAX_APPID_LIST_SIZE = 250;
82 static const std::string MDM_ENABLE_VALUE = "status";
83 static const std::string MDM_BUNDLE_NAME = "appId";
84 static const uint32_t ENABLE_VALUE_TRUE = 1;
85 static const char *FEATURE_INFO_DATA_FILE_PATH = "/data/service/el1/public/dlp_permission_service/dlp_feature_info.txt";
86 }
87 REGISTER_SYSTEM_ABILITY_BY_ID(DlpPermissionService, SA_ID_DLP_PERMISSION_SERVICE, true);
88 
DlpPermissionService(int saId,bool runOnCreate)89 DlpPermissionService::DlpPermissionService(int saId, bool runOnCreate)
90     : SystemAbility(saId, runOnCreate), state_(ServiceRunningState::STATE_NOT_START)
91 {
92     DLP_LOG_INFO(LABEL, "DlpPermissionService()");
93 }
94 
~DlpPermissionService()95 DlpPermissionService::~DlpPermissionService()
96 {
97     DLP_LOG_INFO(LABEL, "~DlpPermissionService()");
98     UnregisterAppStateObserver();
99     iAppMgr_ = nullptr;
100     appStateObserver_ = nullptr;
101     std::unique_lock<std::shared_mutex> lock(dlpSandboxDataMutex_);
102     dlpSandboxData_.clear();
103 }
104 
IsSaCall()105 static bool IsSaCall()
106 {
107     Security::AccessToken::AccessTokenID callingToken = IPCSkeleton::GetCallingTokenID();
108     Security::AccessToken::TypeATokenTypeEnum res = Security::AccessToken::AccessTokenKit::GetTokenType(callingToken);
109     return (res == Security::AccessToken::TOKEN_NATIVE);
110 }
111 
OnStart()112 void DlpPermissionService::OnStart()
113 {
114     if (state_ == ServiceRunningState::STATE_RUNNING) {
115         DLP_LOG_INFO(LABEL, "DlpPermissionService has already started!");
116         return;
117     }
118     DLP_LOG_INFO(LABEL, "DlpPermissionService is starting");
119     if (!RegisterAppStateObserver()) {
120         DLP_LOG_ERROR(LABEL, "Failed to register app state observer!");
121         return;
122     }
123     dlpEventSubSubscriber_ = std::make_shared<DlpEventSubSubscriber>();
124     bool ret = Publish(this);
125     if (!ret) {
126         DLP_LOG_ERROR(LABEL, "Failed to publish service!");
127         return;
128     }
129     state_ = ServiceRunningState::STATE_RUNNING;
130     DLP_LOG_INFO(LABEL, "Congratulations, DlpPermissionService start successfully!");
131 }
132 
OnStop()133 void DlpPermissionService::OnStop()
134 {
135     DLP_LOG_INFO(LABEL, "Stop service");
136     dlpEventSubSubscriber_ = nullptr;
137 }
138 
RegisterAppStateObserver()139 bool DlpPermissionService::RegisterAppStateObserver()
140 {
141     if (appStateObserver_ != nullptr) {
142         DLP_LOG_INFO(LABEL, "AppStateObserver instance already create");
143         return true;
144     }
145     sptr<AppStateObserver> tempAppStateObserver = new (std::nothrow) AppStateObserver();
146     if (tempAppStateObserver == nullptr) {
147         DLP_LOG_ERROR(LABEL, "Failed to create AppStateObserver instance");
148         return false;
149     }
150     sptr<ISystemAbilityManager> samgrClient = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
151     if (samgrClient == nullptr) {
152         DLP_LOG_ERROR(LABEL, "Failed to get system ability manager");
153         return false;
154     }
155     auto obj = samgrClient->GetSystemAbility(APP_MGR_SERVICE_ID);
156     iAppMgr_ = iface_cast<AppExecFwk::IAppMgr>(obj);
157     if (iAppMgr_ == nullptr) {
158         DLP_LOG_ERROR(LABEL, "Failed to get ability manager service");
159         return false;
160     }
161     int32_t result = iAppMgr_->RegisterApplicationStateObserver(tempAppStateObserver);
162     if (result != DLP_OK) {
163         DLP_LOG_ERROR(LABEL, "Failed to Register app state observer");
164         iAppMgr_ = nullptr;
165         return false;
166     }
167     sptr<AppExecFwk::AppMgrProxy> proxy = new (std::nothrow)AppExecFwk::AppMgrProxy(obj);
168     if (proxy == nullptr) {
169         DLP_LOG_ERROR(LABEL, "Failed to create AppMgrProxy instance");
170         iAppMgr_ = nullptr;
171         return false;
172     }
173     appStateObserver_ = tempAppStateObserver;
174     appStateObserver_->SetAppProxy(proxy);
175     return true;
176 }
177 
UnregisterAppStateObserver()178 void DlpPermissionService::UnregisterAppStateObserver()
179 {
180     if (iAppMgr_ != nullptr && appStateObserver_ != nullptr) {
181         iAppMgr_->UnregisterApplicationStateObserver(appStateObserver_);
182     }
183 }
184 
GenerateDlpCertificate(const sptr<DlpPolicyParcel> & policyParcel,const sptr<IDlpPermissionCallback> & callback)185 int32_t DlpPermissionService::GenerateDlpCertificate(
186     const sptr<DlpPolicyParcel>& policyParcel, const sptr<IDlpPermissionCallback>& callback)
187 {
188     if (!AccessTokenAdapter::IsSystemApp()) {
189         return DLP_SERVICE_ERROR_NOT_SYSTEM_APP;
190     }
191     if (!PermissionManagerAdapter::CheckPermission(PERMISSION_ACCESS_DLP_FILE) &&
192         !PermissionManagerAdapter::CheckPermission(PERMISSION_ENTERPRISE_ACCESS_DLP_FILE)) {
193         return DLP_SERVICE_ERROR_PERMISSION_DENY;
194     }
195 
196     if (callback == nullptr) {
197         DLP_LOG_ERROR(LABEL, "Callback is null");
198         return DLP_SERVICE_ERROR_VALUE_INVALID;
199     }
200 
201     if (!policyParcel->policyParams_.IsValid()) {
202         return DLP_SERVICE_ERROR_VALUE_INVALID;
203     }
204     policyParcel->policyParams_.SetDebug(OHOS::system::GetBoolParameter(DEVELOPER_MODE, false));
205     unordered_json jsonObj;
206     int32_t res = DlpPermissionSerializer::GetInstance().SerializeDlpPermission(policyParcel->policyParams_, jsonObj);
207     if (res != DLP_OK) {
208         return res;
209     }
210 
211     return DlpCredential::GetInstance().GenerateDlpCertificate(
212         jsonObj.dump(), policyParcel->policyParams_.ownerAccountId_,
213         policyParcel->policyParams_.ownerAccountType_, callback);
214 }
215 
GetApplicationInfo(std::string appId,AppExecFwk::ApplicationInfo & applicationInfo)216 static bool GetApplicationInfo(std::string appId, AppExecFwk::ApplicationInfo& applicationInfo)
217 {
218     size_t pos = appId.find_last_of(SEPARATOR);
219     if (pos > appId.length()) {
220         DLP_LOG_ERROR(LABEL, "AppId=%{public}s pos=%{public}zu can not find bundleName", appId.c_str(), pos);
221         return false;
222     }
223     std::string bundleName = appId.substr(0, pos);
224 
225     int32_t userId = GetCallingUserId();
226     if (userId < 0) {
227         DLP_LOG_ERROR(LABEL, "Get userId error.");
228         return false;
229     }
230     if (!BundleManagerAdapter::GetInstance().GetApplicationInfo(bundleName,
231         OHOS::AppExecFwk::ApplicationFlag::GET_ALL_APPLICATION_INFO, userId, applicationInfo)) {
232         DLP_LOG_ERROR(LABEL, "Get applicationInfo error bundleName=%{public}s", bundleName.c_str());
233         return false;
234     }
235     return true;
236 }
237 
ParseDlpCertificate(const sptr<CertParcel> & certParcel,const sptr<IDlpPermissionCallback> & callback,const std::string & appId,bool offlineAccess)238 int32_t DlpPermissionService::ParseDlpCertificate(const sptr<CertParcel>& certParcel,
239     const sptr<IDlpPermissionCallback>& callback, const std::string& appId, bool offlineAccess)
240 {
241     if (!AccessTokenAdapter::IsSystemApp()) {
242         return DLP_SERVICE_ERROR_NOT_SYSTEM_APP;
243     }
244     if (!PermissionManagerAdapter::CheckPermission(PERMISSION_ACCESS_DLP_FILE) &&
245         !PermissionManagerAdapter::CheckPermission(PERMISSION_ENTERPRISE_ACCESS_DLP_FILE)) {
246         return DLP_SERVICE_ERROR_PERMISSION_DENY;
247     }
248     if (callback == nullptr) {
249         DLP_LOG_ERROR(LABEL, "Callback is null");
250         return DLP_SERVICE_ERROR_VALUE_INVALID;
251     }
252     if (appId.empty()) {
253         DLP_LOG_ERROR(LABEL, "AppId is empty");
254         return DLP_CREDENTIAL_ERROR_APPID_NOT_AUTHORIZED;
255     }
256     AppExecFwk::ApplicationInfo applicationInfo;
257     if (!GetApplicationInfo(appId, applicationInfo)) {
258         DLP_LOG_ERROR(LABEL, "Permission check fail.");
259         return DLP_SERVICE_ERROR_VALUE_INVALID;
260     }
261     return DlpCredential::GetInstance().ParseDlpCertificate(
262         certParcel, callback, appId, offlineAccess, applicationInfo);
263 }
264 
InsertDlpSandboxInfo(DlpSandboxInfo & sandboxInfo,bool hasRetention)265 bool DlpPermissionService::InsertDlpSandboxInfo(DlpSandboxInfo& sandboxInfo, bool hasRetention)
266 {
267     AppExecFwk::BundleInfo info;
268     AppExecFwk::BundleMgrClient bundleMgrClient;
269     if (bundleMgrClient.GetSandboxBundleInfo(sandboxInfo.bundleName, sandboxInfo.appIndex, sandboxInfo.userId, info) !=
270         DLP_OK) {
271         DLP_LOG_ERROR(LABEL, "Get sandbox bundle info fail appIndex=%{public}d", sandboxInfo.appIndex);
272         if (hasRetention) {
273             RetentionFileManager::GetInstance().ClearUnreservedSandbox();
274         }
275         return false;
276     }
277     sandboxInfo.uid = info.uid;
278     sandboxInfo.tokenId = AccessToken::AccessTokenKit::GetHapTokenID(sandboxInfo.userId, sandboxInfo.bundleName,
279         sandboxInfo.appIndex);
280     appStateObserver_->AddDlpSandboxInfo(sandboxInfo);
281     VisitRecordFileManager::GetInstance().AddVisitRecord(sandboxInfo.bundleName, sandboxInfo.userId, sandboxInfo.uri);
282     return true;
283 }
284 
GetAppIndexFromRetentionInfo(const std::string & bundleName,bool isReadOnly,const std::string & uri,DlpSandboxInfo & dlpSandBoxInfo,bool & isNeedInstall)285 static int32_t GetAppIndexFromRetentionInfo(const std::string& bundleName, bool isReadOnly, const std::string& uri,
286     DlpSandboxInfo& dlpSandBoxInfo, bool& isNeedInstall)
287 {
288     std::vector<RetentionSandBoxInfo> infoVec;
289     auto res = RetentionFileManager::GetInstance().GetRetentionSandboxList(bundleName, infoVec, true);
290     if (res != DLP_OK) {
291         DLP_LOG_ERROR(LABEL, "GetRetentionSandboxList fail bundleName:%{public}s, error=%{public}d",
292             bundleName.c_str(), res);
293         return res;
294     }
295     for (auto iter = infoVec.begin(); iter != infoVec.end(); ++iter) {
296         if (isReadOnly && iter->dlpFileAccess_ == DLPFileAccess::READ_ONLY) {
297             dlpSandBoxInfo.appIndex = iter->appIndex_;
298             dlpSandBoxInfo.hasRead = iter->hasRead_;
299             isNeedInstall = false;
300             break;
301         }
302         if (isReadOnly) {
303             continue;
304         }
305         auto setIter = iter->docUriSet_.find(uri);
306         if (setIter != iter->docUriSet_.end()) {
307             dlpSandBoxInfo.appIndex = iter->appIndex_;
308             dlpSandBoxInfo.hasRead = iter->hasRead_;
309             isNeedInstall = false;
310             break;
311         }
312     }
313     return DLP_OK;
314 }
315 
CheckWithInstallDlpSandbox(const std::string & bundleName,DLPFileAccess dlpFileAccess)316 static int32_t CheckWithInstallDlpSandbox(const std::string& bundleName, DLPFileAccess dlpFileAccess)
317 {
318     if (!PermissionManagerAdapter::CheckPermission(PERMISSION_ACCESS_DLP_FILE)) {
319         return DLP_SERVICE_ERROR_PERMISSION_DENY;
320     }
321     if (bundleName.empty() ||
322         dlpFileAccess > DLPFileAccess::FULL_CONTROL || dlpFileAccess <= DLPFileAccess::NO_PERMISSION) {
323         DLP_LOG_ERROR(LABEL, "param is invalid");
324         return DLP_SERVICE_ERROR_VALUE_INVALID;
325     }
326     return DLP_OK;
327 }
328 
FillDlpSandboxInfo(DlpSandboxInfo & dlpSandboxInfo,const std::string & bundleName,DLPFileAccess dlpFileAccess,int32_t userId,const std::string & uri)329 static void FillDlpSandboxInfo(DlpSandboxInfo& dlpSandboxInfo, const std::string& bundleName,
330     DLPFileAccess dlpFileAccess, int32_t userId, const std::string& uri)
331 {
332     dlpSandboxInfo.bundleName = bundleName;
333     dlpSandboxInfo.dlpFileAccess = dlpFileAccess;
334     dlpSandboxInfo.userId = userId;
335     dlpSandboxInfo.pid = IPCSkeleton::GetCallingRealPid();
336     dlpSandboxInfo.uri = uri;
337     dlpSandboxInfo.timeStamp = static_cast<uint64_t>(
338         std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count());
339 }
340 
InstallDlpSandbox(const std::string & bundleName,DLPFileAccess dlpFileAccess,int32_t userId,SandboxInfo & sandboxInfo,const std::string & uri)341 int32_t DlpPermissionService::InstallDlpSandbox(const std::string& bundleName, DLPFileAccess dlpFileAccess,
342     int32_t userId, SandboxInfo& sandboxInfo, const std::string& uri)
343 {
344     if (!AccessTokenAdapter::IsSystemApp()) {
345         return DLP_SERVICE_ERROR_NOT_SYSTEM_APP;
346     }
347     int32_t res = CheckWithInstallDlpSandbox(bundleName, dlpFileAccess);
348     if (res != DLP_OK) {
349         return res;
350     }
351     if (appStateObserver_->GetOpeningSandboxInfo(bundleName, uri, userId, sandboxInfo)) {
352         return DLP_OK;
353     }
354     bool isReadOnly = dlpFileAccess == DLPFileAccess::READ_ONLY;
355     bool isNeedInstall = true;
356     DlpSandboxInfo dlpSandboxInfo;
357     res = GetAppIndexFromRetentionInfo(bundleName, isReadOnly, uri, dlpSandboxInfo, isNeedInstall);
358     if (res != DLP_OK) {
359         return res;
360     }
361     if (isNeedInstall && isReadOnly) {
362         appStateObserver_->GetOpeningReadOnlySandbox(bundleName, userId, dlpSandboxInfo.appIndex);
363         isNeedInstall = (dlpSandboxInfo.appIndex != -1) ? false : true;
364     }
365     if (isNeedInstall) {
366         AppExecFwk::BundleMgrClient bundleMgrClient;
367         DLPFileAccess permForBMS =
368             (dlpFileAccess == DLPFileAccess::READ_ONLY) ? DLPFileAccess::READ_ONLY : DLPFileAccess::CONTENT_EDIT;
369         int32_t bundleClientRes = bundleMgrClient.InstallSandboxApp(bundleName,
370             static_cast<int32_t>(permForBMS), userId, dlpSandboxInfo.appIndex);
371         if (bundleClientRes != DLP_OK) {
372             DLP_LOG_ERROR(LABEL, "install sandbox %{public}s fail, error=%{public}d", bundleName.c_str(),
373                 bundleClientRes);
374             return DLP_SERVICE_ERROR_INSTALL_SANDBOX_FAIL;
375         }
376     }
377     FillDlpSandboxInfo(dlpSandboxInfo, bundleName, dlpFileAccess, userId, uri);
378     if (!InsertDlpSandboxInfo(dlpSandboxInfo, !isNeedInstall)) {
379         return DLP_SERVICE_ERROR_INSTALL_SANDBOX_FAIL;
380     }
381     sandboxInfo.appIndex = dlpSandboxInfo.appIndex;
382     sandboxInfo.tokenId = dlpSandboxInfo.tokenId;
383     std::unique_lock<std::shared_mutex> lock(dlpSandboxDataMutex_);
384     auto it = dlpSandboxData_.find(dlpSandboxInfo.uid);
385     if (it == dlpSandboxData_.end()) {
386         dlpSandboxData_.insert(std::make_pair(dlpSandboxInfo.uid, dlpSandboxInfo.dlpFileAccess));
387     }
388     return DLP_OK;
389 }
390 
DeleteDlpSandboxInfo(const std::string & bundleName,int32_t appIndex,int32_t userId)391 uint32_t DlpPermissionService::DeleteDlpSandboxInfo(const std::string& bundleName, int32_t appIndex, int32_t userId)
392 {
393     AppExecFwk::BundleMgrClient bundleMgrClient;
394     AppExecFwk::BundleInfo info;
395     int32_t result = bundleMgrClient.GetSandboxBundleInfo(bundleName, appIndex, userId, info);
396     if (result != DLP_OK) {
397         DLP_LOG_ERROR(LABEL, "Get sandbox bundle info fail");
398         return 0;
399     }
400 
401     std::unique_lock<std::shared_mutex> lock(dlpSandboxDataMutex_);
402     auto it = dlpSandboxData_.find(info.uid);
403     if (it != dlpSandboxData_.end()) {
404         dlpSandboxData_.erase(info.uid);
405     }
406 
407     return appStateObserver_->EraseDlpSandboxInfo(info.uid);
408 }
409 
UninstallDlpSandboxApp(const std::string & bundleName,int32_t appIndex,int32_t userId)410 int32_t DlpPermissionService::UninstallDlpSandboxApp(const std::string& bundleName, int32_t appIndex, int32_t userId)
411 {
412     AppExecFwk::BundleMgrClient bundleMgrClient;
413     int32_t res = bundleMgrClient.UninstallSandboxApp(bundleName, appIndex, userId);
414     if (res != DLP_OK) {
415         DLP_LOG_ERROR(LABEL, "uninstall sandbox %{public}s fail, index=%{public}d, error=%{public}d",
416             bundleName.c_str(), appIndex, res);
417         return DLP_SERVICE_ERROR_UNINSTALL_SANDBOX_FAIL;
418     }
419     return DLP_OK;
420 }
421 
UninstallDlpSandbox(const std::string & bundleName,int32_t appIndex,int32_t userId)422 int32_t DlpPermissionService::UninstallDlpSandbox(const std::string& bundleName, int32_t appIndex, int32_t userId)
423 {
424     if (!AccessTokenAdapter::IsSystemApp()) {
425         return DLP_SERVICE_ERROR_NOT_SYSTEM_APP;
426     }
427     if (!PermissionManagerAdapter::CheckPermission(PERMISSION_ACCESS_DLP_FILE)) {
428         return DLP_SERVICE_ERROR_PERMISSION_DENY;
429     }
430 
431     if (bundleName.empty() || appIndex < 0 || userId < 0) {
432         DLP_LOG_ERROR(LABEL, "param is invalid");
433         return DLP_SERVICE_ERROR_VALUE_INVALID;
434     }
435 
436     uint32_t tokenId = DeleteDlpSandboxInfo(bundleName, appIndex, userId);
437     if (tokenId == 0) {
438         DLP_LOG_ERROR(LABEL, "DeleteDlpSandboxInfo sandbox %{public}s fail, index=%{public}d", bundleName.c_str(),
439             appIndex);
440         return DLP_SERVICE_ERROR_UNINSTALL_SANDBOX_FAIL;
441     }
442     if (RetentionFileManager::GetInstance().CanUninstall(tokenId)) {
443         return UninstallDlpSandboxApp(bundleName, appIndex, userId);
444     }
445     return DLP_OK;
446 }
447 
CheckAllowAbilityList(const AAFwk::Want & want)448 static bool CheckAllowAbilityList(const AAFwk::Want& want)
449 {
450     std::string bundleName = want.GetBundle();
451     std::string actionName = want.GetAction();
452     DLP_LOG_DEBUG(LABEL, "CheckAllowAbilityList %{public}s %{public}s", bundleName.c_str(), actionName.c_str());
453     bool bundleCheck = (bundleName == DLP_MANAGER) &&
454         BundleManagerAdapter::GetInstance().CheckHapPermission(bundleName, PERMISSION_ACCESS_DLP_FILE);
455     bool actionCheck = std::any_of(std::begin(ALLOW_ACTION), std::end(ALLOW_ACTION),
456         [actionName](const std::string& action) { return action == actionName; });
457     return actionCheck || bundleCheck;
458 }
459 
GetSandboxExternalAuthorization(int sandboxUid,const AAFwk::Want & want,SandBoxExternalAuthorType & authType)460 int32_t DlpPermissionService::GetSandboxExternalAuthorization(
461     int sandboxUid, const AAFwk::Want& want, SandBoxExternalAuthorType& authType)
462 {
463     if (!IsSaCall() && !PermissionManagerAdapter::CheckPermission(PERMISSION_ACCESS_DLP_FILE)) {
464         DLP_LOG_ERROR(LABEL, "Caller is not SA or has no ACCESS_DLP_FILE permission");
465         return DLP_SERVICE_ERROR_PARCEL_OPERATE_FAIL;
466     }
467     if (sandboxUid < 0) {
468         DLP_LOG_ERROR(LABEL, "param is invalid");
469         return DLP_SERVICE_ERROR_VALUE_INVALID;
470     }
471     bool isSandbox = false;
472 
473     appStateObserver_->IsInDlpSandbox(isSandbox, sandboxUid);
474 
475     std::unique_lock<std::shared_mutex> lock(dlpSandboxDataMutex_);
476     auto it = dlpSandboxData_.find(sandboxUid);
477     if (isSandbox && it != dlpSandboxData_.end() && dlpSandboxData_[sandboxUid] != DLPFileAccess::READ_ONLY) {
478         authType = SandBoxExternalAuthorType::ALLOW_START_ABILITY;
479         return DLP_OK;
480     }
481 
482     if (isSandbox && !CheckAllowAbilityList(want)) {
483         authType = SandBoxExternalAuthorType::DENY_START_ABILITY;
484     } else {
485         authType = SandBoxExternalAuthorType::ALLOW_START_ABILITY;
486     }
487 
488     return DLP_OK;
489 }
490 
QueryDlpFileCopyableByTokenId(bool & copyable,uint32_t tokenId)491 int32_t DlpPermissionService::QueryDlpFileCopyableByTokenId(bool& copyable, uint32_t tokenId)
492 {
493     if (tokenId == 0) {
494         return DLP_SERVICE_ERROR_VALUE_INVALID;
495     }
496     return appStateObserver_->QueryDlpFileCopyableByTokenId(copyable, tokenId);
497 }
498 
GetDlpActionFlag(DLPFileAccess dlpFileAccess)499 static ActionFlags GetDlpActionFlag(DLPFileAccess dlpFileAccess)
500 {
501     switch (dlpFileAccess) {
502         case DLPFileAccess::READ_ONLY: {
503             return ACTION_VIEW;
504         }
505         case DLPFileAccess::CONTENT_EDIT: {
506             return static_cast<ActionFlags>(ACTION_VIEW | ACTION_SAVE | ACTION_SAVE_AS | ACTION_EDIT |
507             ACTION_SCREEN_CAPTURE | ACTION_SCREEN_SHARE | ACTION_SCREEN_RECORD | ACTION_COPY);
508         }
509         case DLPFileAccess::FULL_CONTROL: {
510             return static_cast<ActionFlags>(ACTION_VIEW | ACTION_SAVE | ACTION_SAVE_AS | ACTION_EDIT |
511                 ACTION_SCREEN_CAPTURE | ACTION_SCREEN_SHARE | ACTION_SCREEN_RECORD | ACTION_COPY | ACTION_PRINT |
512                 ACTION_EXPORT | ACTION_PERMISSION_CHANGE);
513         }
514         default:
515             return ACTION_INVALID;
516     }
517 }
518 
QueryDlpFileAccess(DLPPermissionInfoParcel & permInfoParcel)519 int32_t DlpPermissionService::QueryDlpFileAccess(DLPPermissionInfoParcel& permInfoParcel)
520 {
521     bool sandboxFlag;
522     if (PermissionManagerAdapter::CheckSandboxFlagWithService(GetCallingTokenID(), sandboxFlag) != DLP_OK) {
523         return DLP_SERVICE_ERROR_VALUE_INVALID;
524     }
525     if (!sandboxFlag) {
526         DLP_LOG_ERROR(LABEL, "Forbid called by a non-sandbox app");
527         return DLP_SERVICE_ERROR_API_ONLY_FOR_SANDBOX_ERROR;
528     }
529     int32_t uid = IPCSkeleton::GetCallingUid();
530     DLPFileAccess dlpFileAccess = DLPFileAccess::NO_PERMISSION;
531     int32_t res = appStateObserver_->QueryDlpFileAccessByUid(dlpFileAccess, uid);
532     permInfoParcel.permInfo_.dlpFileAccess = dlpFileAccess;
533     permInfoParcel.permInfo_.flags = GetDlpActionFlag(dlpFileAccess);
534     return res;
535 }
536 
IsInDlpSandbox(bool & inSandbox)537 int32_t DlpPermissionService::IsInDlpSandbox(bool& inSandbox)
538 {
539     int32_t uid = IPCSkeleton::GetCallingUid();
540     return appStateObserver_->IsInDlpSandbox(inSandbox, uid);
541 }
542 
GetCfgFilesList(std::vector<std::string> & cfgFilesList)543 void DlpPermissionService::GetCfgFilesList(std::vector<std::string>& cfgFilesList)
544 {
545     CfgFiles *cfgFiles = GetCfgFiles(DLP_CONFIG.c_str()); // need free
546     if (cfgFiles != nullptr) {
547         for (auto& cfgPath : cfgFiles->paths) {
548             if (cfgPath != nullptr) {
549                 cfgFilesList.emplace_back(cfgPath);
550             }
551         }
552         FreeCfgFiles(cfgFiles); // free memory
553     }
554     std::reverse(cfgFilesList.begin(), cfgFilesList.end()); // priority from low to high, need reverse
555 }
556 
GetConfigFileValue(const std::string & cfgFile,std::vector<std::string> & typeList)557 void DlpPermissionService::GetConfigFileValue(const std::string& cfgFile, std::vector<std::string>& typeList)
558 {
559     std::string content;
560     (void)FileOperator().GetFileContentByPath(cfgFile, content);
561     if (content.empty()) {
562         return ;
563     }
564     auto jsonObj = nlohmann::json::parse(content, nullptr, false);
565     if (jsonObj.is_discarded() || (!jsonObj.is_object())) {
566         DLP_LOG_WARN(LABEL, "JsonObj is discarded");
567         return ;
568     }
569     auto result = jsonObj.find(SUPPORT_FILE_TYPE);
570     if (result != jsonObj.end() && result->is_array() && !result->empty() && (*result)[0].is_string()) {
571         typeList = result->get<std::vector<std::string>>();
572     }
573 }
574 
InitConfig(std::vector<std::string> & typeList)575 void DlpPermissionService::InitConfig(std::vector<std::string>& typeList)
576 {
577     static std::vector<std::string> typeListTemp;
578     static bool cfgInit = true;
579     std::lock_guard<std::mutex> lock(mutex_);
580     if (cfgInit) {
581         cfgInit = false;
582         std::vector<std::string> cfgFilesList;
583         GetCfgFilesList(cfgFilesList);
584         for (const auto& cfgFile : cfgFilesList) {
585             GetConfigFileValue(cfgFile, typeListTemp);
586             if (!typeListTemp.empty()) {
587                 typeList = typeListTemp;
588                 return;
589             }
590         }
591         DLP_LOG_INFO(LABEL, "get config value failed, use default file path");
592         GetConfigFileValue(DEAULT_DLP_CONFIG, typeListTemp);
593         if (typeListTemp.empty()) {
594             DLP_LOG_ERROR(LABEL, "support file type list is empty");
595         }
596     }
597     typeList = typeListTemp;
598 }
599 
GetDlpSupportFileType(std::vector<std::string> & supportFileType)600 int32_t DlpPermissionService::GetDlpSupportFileType(std::vector<std::string>& supportFileType)
601 {
602     SetTimer(true);
603     InitConfig(supportFileType);
604     if (supportFileType.size() > MAX_SUPPORT_FILE_TYPE_NUM) {
605         DLP_LOG_ERROR(LABEL, "listNum larger than 1024");
606         return DLP_SERVICE_ERROR_PARCEL_OPERATE_FAIL;
607     }
608     return DLP_OK;
609 }
610 
RegisterDlpSandboxChangeCallback(const sptr<IRemoteObject> & callback)611 int32_t DlpPermissionService::RegisterDlpSandboxChangeCallback(const sptr<IRemoteObject>& callback)
612 {
613     if (!PermissionManagerAdapter::CheckPermission(PERMISSION_ACCESS_DLP_FILE)) {
614         return DLP_SERVICE_ERROR_PERMISSION_DENY;
615     }
616     int32_t pid = IPCSkeleton::GetCallingRealPid();
617     DLP_LOG_INFO(LABEL, "GetCallingRealPid,%{public}d", pid);
618     return DlpSandboxChangeCallbackManager::GetInstance().AddCallback(pid, callback);
619 }
620 
UnRegisterDlpSandboxChangeCallback(bool & result)621 int32_t DlpPermissionService::UnRegisterDlpSandboxChangeCallback(bool& result)
622 {
623     if (!PermissionManagerAdapter::CheckPermission(PERMISSION_ACCESS_DLP_FILE)) {
624         return DLP_SERVICE_ERROR_PERMISSION_DENY;
625     }
626     int32_t pid = IPCSkeleton::GetCallingRealPid();
627     DLP_LOG_INFO(LABEL, "GetCallingRealPid,%{public}d", pid);
628     return DlpSandboxChangeCallbackManager::GetInstance().RemoveCallback(pid, result);
629 }
630 
RegisterOpenDlpFileCallback(const sptr<IRemoteObject> & callback)631 int32_t DlpPermissionService::RegisterOpenDlpFileCallback(const sptr<IRemoteObject>& callback)
632 {
633     bool sandboxFlag;
634     if (PermissionManagerAdapter::CheckSandboxFlagWithService(GetCallingTokenID(), sandboxFlag) != DLP_OK) {
635         return DLP_SERVICE_ERROR_VALUE_INVALID;
636     }
637     if (sandboxFlag) {
638         DLP_LOG_ERROR(LABEL, "Forbid called by a sandbox app");
639         return DLP_SERVICE_ERROR_API_NOT_FOR_SANDBOX_ERROR;
640     }
641     std::string callerBundleName;
642     if (!GetCallerBundleName(IPCSkeleton::GetCallingTokenID(), callerBundleName)) {
643         DLP_LOG_ERROR(LABEL, "get callerBundleName error");
644         return DLP_SERVICE_ERROR_VALUE_INVALID;
645     }
646     int32_t uid = IPCSkeleton::GetCallingUid();
647     int32_t userId;
648     if (GetUserIdFromUid(uid, &userId) != 0) {
649         DLP_LOG_ERROR(LABEL, "GetUserIdFromUid error");
650         return DLP_SERVICE_ERROR_VALUE_INVALID;
651     }
652     int32_t pid = IPCSkeleton::GetCallingRealPid();
653 
654     DLP_LOG_INFO(LABEL, "CallingPid: %{public}d, userId: %{public}d, CallingBundle: %{public}s", pid, userId,
655         callerBundleName.c_str());
656 
657     int res = OpenDlpFileCallbackManager::GetInstance().AddCallback(pid, userId, callerBundleName, callback);
658     if (res != DLP_OK) {
659         return res;
660     }
661     appStateObserver_->AddCallbackListener(pid);
662     return DLP_OK;
663 }
664 
UnRegisterOpenDlpFileCallback(const sptr<IRemoteObject> & callback)665 int32_t DlpPermissionService::UnRegisterOpenDlpFileCallback(const sptr<IRemoteObject>& callback)
666 {
667     SetTimer(true);
668 
669     bool sandboxFlag;
670     if (PermissionManagerAdapter::CheckSandboxFlagWithService(GetCallingTokenID(), sandboxFlag) != DLP_OK) {
671         return DLP_SERVICE_ERROR_VALUE_INVALID;
672     }
673     if (sandboxFlag) {
674         DLP_LOG_ERROR(LABEL, "Forbid called by a sandbox app");
675         return DLP_SERVICE_ERROR_API_NOT_FOR_SANDBOX_ERROR;
676     }
677     int32_t pid = IPCSkeleton::GetCallingRealPid();
678     int32_t res = OpenDlpFileCallbackManager::GetInstance().RemoveCallback(pid, callback);
679     appStateObserver_->RemoveCallbackListener(pid);
680     return res;
681 }
682 
GetDlpGatheringPolicy(bool & isGathering)683 int32_t DlpPermissionService::GetDlpGatheringPolicy(bool& isGathering)
684 {
685     if (!PermissionManagerAdapter::CheckPermission(PERMISSION_ACCESS_DLP_FILE)) {
686         return DLP_SERVICE_ERROR_PERMISSION_DENY;
687     }
688 
689     isGathering = true;
690 #if defined(DLP_DEBUG_ENABLE) && DLP_DEBUG_ENABLE == 1
691     const char* PARAM_KEY = "dlp.permission.gathering.policy";
692     const int32_t VALUE_MAX_LEN = 32;
693     char value[VALUE_MAX_LEN] = {0};
694     int32_t ret = GetParameter(PARAM_KEY, "false", value, VALUE_MAX_LEN - 1);
695     if (ret <= 0) {
696         DLP_LOG_WARN(LABEL, "Failed to get parameter, %{public}s", PARAM_KEY);
697         return DLP_OK;
698     }
699 
700     std::string tmp(value);
701     if (tmp == "true") {
702         isGathering = true;
703     }
704 
705     if (tmp == "false") {
706         isGathering = false;
707     }
708 #endif
709     return DLP_OK;
710 }
711 
SetRetentionState(const std::vector<std::string> & docUriVec)712 int32_t DlpPermissionService::SetRetentionState(const std::vector<std::string>& docUriVec)
713 {
714     bool sandboxFlag;
715     if (PermissionManagerAdapter::CheckSandboxFlagWithService(GetCallingTokenID(), sandboxFlag) != DLP_OK) {
716         return DLP_SERVICE_ERROR_VALUE_INVALID;
717     }
718     if (!sandboxFlag) {
719         DLP_LOG_ERROR(LABEL, "Forbid called by a non-sandbox app");
720         return DLP_SERVICE_ERROR_API_ONLY_FOR_SANDBOX_ERROR;
721     }
722     if (docUriVec.empty()) {
723         DLP_LOG_ERROR(LABEL, "get docUriVec empty");
724         return DLP_SERVICE_ERROR_VALUE_INVALID;
725     }
726     RetentionInfo info;
727     info.tokenId = IPCSkeleton::GetCallingTokenID();
728     std::set<std::string> docUriSet(docUriVec.begin(), docUriVec.end());
729     int32_t uid = IPCSkeleton::GetCallingUid();
730     DlpSandboxInfo sandboxInfo;
731     bool result = appStateObserver_->GetSandboxInfo(uid, sandboxInfo);
732     if (!result) {
733         DLP_LOG_ERROR(LABEL, "Can not found sandbox info");
734         return DLP_SERVICE_ERROR_VALUE_INVALID;
735     }
736     info.hasRead = sandboxInfo.hasRead;
737     return RetentionFileManager::GetInstance().UpdateSandboxInfo(docUriSet, info, true);
738 }
739 
CancelRetentionState(const std::vector<std::string> & docUriVec)740 int32_t DlpPermissionService::CancelRetentionState(const std::vector<std::string>& docUriVec)
741 {
742     SetTimer(true);
743     if (docUriVec.empty()) {
744         DLP_LOG_ERROR(LABEL, "get docUriVec empty");
745         return DLP_SERVICE_ERROR_VALUE_INVALID;
746     }
747     RetentionInfo info;
748     info.tokenId = IPCSkeleton::GetCallingTokenID();
749     if (!GetCallerBundleName(info.tokenId, info.bundleName)) {
750         DLP_LOG_ERROR(LABEL, "get callerBundleName error");
751         return DLP_SERVICE_ERROR_VALUE_INVALID;
752     }
753     bool isInSandbox = false;
754     IsInDlpSandbox(isInSandbox);
755     if (!isInSandbox) {
756         info.tokenId = 0;
757     }
758     int32_t res = 0;
759     {
760         std::lock_guard<std::mutex> lock(terminalMutex_);
761         std::set<std::string> docUriSet(docUriVec.begin(), docUriVec.end());
762         res = RetentionFileManager::GetInstance().UpdateSandboxInfo(docUriSet, info, false);
763         if (isInSandbox) {
764             return res;
765         }
766         std::vector<RetentionSandBoxInfo> retentionSandBoxInfoVec;
767         int32_t getRes = RetentionFileManager::GetInstance().GetRetentionSandboxList(info.bundleName,
768             retentionSandBoxInfoVec, false);
769         if (getRes != DLP_OK) {
770             DLP_LOG_ERROR(LABEL, "getRes != DLP_OK");
771             return getRes;
772         }
773         if (!retentionSandBoxInfoVec.empty()) {
774             if (!RemoveRetentionInfo(retentionSandBoxInfoVec, info)) {
775                 return DLP_SERVICE_ERROR_VALUE_INVALID;
776             }
777         }
778     }
779     return res;
780 }
781 
RemoveRetentionInfo(std::vector<RetentionSandBoxInfo> & retentionSandBoxInfoVec,RetentionInfo & info)782 bool DlpPermissionService::RemoveRetentionInfo(std::vector<RetentionSandBoxInfo>& retentionSandBoxInfoVec,
783     RetentionInfo& info)
784 {
785     int32_t uid = IPCSkeleton::GetCallingUid();
786     int32_t userId;
787     if (GetUserIdFromUid(uid, &userId) != 0) {
788         DLP_LOG_ERROR(LABEL, "get GetUserIdFromUid error");
789         return false;
790     }
791     for (auto iter = retentionSandBoxInfoVec.begin(); iter != retentionSandBoxInfoVec.end(); ++iter) {
792         if (appStateObserver_->CheckSandboxInfo(info.bundleName, iter->appIndex_, userId)) {
793             continue;
794         }
795         DeleteDlpSandboxInfo(info.bundleName, iter->appIndex_, userId);
796         UninstallDlpSandboxApp(info.bundleName, iter->appIndex_, userId);
797         RetentionFileManager::GetInstance().RemoveRetentionState(info.bundleName, iter->appIndex_);
798     }
799     return true;
800 }
801 
StartTimer()802 void DlpPermissionService::StartTimer()
803 {
804     std::lock_guard<std::mutex> lock(mutex_);
805     repeatTime_ = REPEAT_TIME;
806     if (thread_ != nullptr && !thread_->joinable()) { // avoid double assign to an active thread
807         DLP_LOG_ERROR(LABEL, "thread is active");
808         return;
809     }
810     thread_ = std::make_shared<std::thread>([this] { this->TerminalService(); });
811     thread_->detach();
812     return;
813 }
814 
TerminalService()815 void DlpPermissionService::TerminalService()
816 {
817     DLP_LOG_DEBUG(LABEL, "enter");
818     int32_t remainingTime = repeatTime_.load();
819     while (remainingTime > 0) {
820         std::this_thread::sleep_for(SLEEP_TIME);
821         repeatTime_--;
822         remainingTime = repeatTime_.load();
823         DLP_LOG_DEBUG(LABEL, "repeatTime_ %{public}d", remainingTime);
824     }
825     std::lock_guard<std::mutex> lock(terminalMutex_);
826     appStateObserver_->ExitSaAfterAllDlpManagerDie();
827 }
828 
GetRetentionSandboxList(const std::string & bundleName,std::vector<RetentionSandBoxInfo> & retentionSandBoxInfoVec)829 int32_t DlpPermissionService::GetRetentionSandboxList(const std::string& bundleName,
830     std::vector<RetentionSandBoxInfo>& retentionSandBoxInfoVec)
831 {
832     bool sandboxFlag;
833     if (PermissionManagerAdapter::CheckSandboxFlagWithService(GetCallingTokenID(), sandboxFlag) != DLP_OK) {
834         return DLP_SERVICE_ERROR_VALUE_INVALID;
835     }
836     if (sandboxFlag) {
837         DLP_LOG_ERROR(LABEL, "Forbid called by a sandbox app");
838         return DLP_SERVICE_ERROR_API_NOT_FOR_SANDBOX_ERROR;
839     }
840     std::string callerBundleName;
841     uint32_t tokenId = IPCSkeleton::GetCallingTokenID();
842     GetCallerBundleName(tokenId, callerBundleName);
843     if (callerBundleName == DLP_MANAGER &&
844         BundleManagerAdapter::GetInstance().CheckHapPermission(callerBundleName, PERMISSION_ACCESS_DLP_FILE)) {
845         callerBundleName = bundleName;
846     }
847     if (callerBundleName.empty()) {
848         DLP_LOG_ERROR(LABEL, "get bundleName error");
849         return DLP_SERVICE_ERROR_VALUE_INVALID;
850     }
851     int32_t res =
852         RetentionFileManager::GetInstance().GetRetentionSandboxList(callerBundleName, retentionSandBoxInfoVec, true);
853     if (retentionSandBoxInfoVec.size() > MAX_RETENTION_SIZE) {
854         DLP_LOG_ERROR(LABEL, "size larger than 1024");
855         return DLP_SERVICE_ERROR_PARCEL_OPERATE_FAIL;
856     }
857     return res;
858 }
859 
ClearKvStorage()860 static void ClearKvStorage()
861 {
862     int32_t userId;
863     if (!GetUserIdByForegroundAccount(&userId)) {
864         DLP_LOG_ERROR(LABEL, "get userID fail");
865         return;
866     }
867     std::map<std::string, std::string> keyMap;
868     SandboxConfigKvDataStorage::GetInstance().GetKeyMapByUserId(userId, keyMap);
869     for (auto iter = keyMap.begin(); iter != keyMap.end(); iter++) {
870         AccessTokenID tokenId = AccessToken::AccessTokenKit::GetHapTokenID(userId, iter->first, 0);
871         if (tokenId == 0 || std::to_string(tokenId) != iter->second) {
872             SandboxConfigKvDataStorage::GetInstance().DeleteSandboxConfigFromDataStorage(userId,
873                 iter->first, iter->second);
874         }
875     }
876 }
877 
ClearUnreservedSandbox()878 int32_t DlpPermissionService::ClearUnreservedSandbox()
879 {
880     SetTimer(true);
881 
882     Security::AccessToken::AccessTokenID callingToken = IPCSkeleton::GetCallingTokenID();
883     Security::AccessToken::AccessTokenID bmsToken =
884         Security::AccessToken::AccessTokenKit::GetNativeTokenId(FOUNDATION_SERVICE_NAME);
885     if (callingToken != bmsToken) {
886         return DLP_SERVICE_ERROR_PERMISSION_DENY;
887     }
888 
889     std::lock_guard<std::mutex> lock(terminalMutex_);
890     ClearKvStorage();
891     RetentionFileManager::GetInstance().ClearUnreservedSandbox();
892     return DLP_OK;
893 }
894 
GetCallerBundleName(const uint32_t tokenId,std::string & bundleName)895 bool DlpPermissionService::GetCallerBundleName(const uint32_t tokenId, std::string& bundleName)
896 {
897     HapTokenInfo tokenInfo;
898     auto result = AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo);
899     if (result != RET_SUCCESS) {
900         DLP_LOG_ERROR(LABEL, "token:0x%{public}x, result:%{public}d", tokenId, result);
901         return false;
902     }
903     if (tokenInfo.bundleName.empty()) {
904         DLP_LOG_ERROR(LABEL, "bundlename is empty");
905         return false;
906     }
907     bundleName = tokenInfo.bundleName;
908     return true;
909 }
910 
GetDLPFileVisitRecord(std::vector<VisitedDLPFileInfo> & infoVec)911 int32_t DlpPermissionService::GetDLPFileVisitRecord(std::vector<VisitedDLPFileInfo>& infoVec)
912 {
913     SetTimer(true);
914 
915     bool sandboxFlag;
916     if (PermissionManagerAdapter::CheckSandboxFlagWithService(GetCallingTokenID(), sandboxFlag) != DLP_OK) {
917         return DLP_SERVICE_ERROR_VALUE_INVALID;
918     }
919     if (sandboxFlag) {
920         DLP_LOG_ERROR(LABEL, "Forbid called by a sandbox app");
921         return DLP_SERVICE_ERROR_API_NOT_FOR_SANDBOX_ERROR;
922     }
923 
924     std::string callerBundleName;
925     uint32_t tokenId = IPCSkeleton::GetCallingTokenID();
926     if (!GetCallerBundleName(tokenId, callerBundleName)) {
927         return DLP_SERVICE_ERROR_VALUE_INVALID;
928     }
929     int32_t userId = GetCallingUserId();
930     if (userId < 0) {
931         DLP_LOG_ERROR(LABEL, "get userId error");
932         return DLP_SERVICE_ERROR_VALUE_INVALID;
933     }
934     int32_t result = DLP_OK;
935     {
936         std::lock_guard<std::mutex> lock(terminalMutex_);
937         result = VisitRecordFileManager::GetInstance().GetVisitRecordList(callerBundleName, userId, infoVec);
938     }
939     if (infoVec.size() > MAX_FILE_RECORD_SIZE) {
940         DLP_LOG_ERROR(LABEL, "listNum larger than 1024");
941         return DLP_SERVICE_ERROR_PARCEL_OPERATE_FAIL;
942     }
943     return result;
944 }
945 
SetMDMPolicy(const std::vector<std::string> & appIdList)946 int32_t DlpPermissionService::SetMDMPolicy(const std::vector<std::string>& appIdList)
947 {
948     SetTimer(true);
949     if (appIdList.empty()) {
950         DLP_LOG_ERROR(LABEL, "get appIdList empty");
951         return DLP_SERVICE_ERROR_VALUE_INVALID;
952     }
953     int32_t uid = IPCSkeleton::GetCallingUid();
954     if (uid != EDM_UID) {
955         DLP_LOG_ERROR(LABEL, "invalid caller");
956         return DLP_SERVICE_ERROR_PERMISSION_DENY;
957     }
958     return DlpCredential::GetInstance().SetMDMPolicy(appIdList);
959 }
960 
GetMDMPolicy(std::vector<std::string> & appIdList)961 int32_t DlpPermissionService::GetMDMPolicy(std::vector<std::string>& appIdList)
962 {
963     SetTimer(true);
964     int32_t uid = IPCSkeleton::GetCallingUid();
965     if (uid != EDM_UID) {
966         DLP_LOG_ERROR(LABEL, "invalid caller");
967         return DLP_SERVICE_ERROR_PERMISSION_DENY;
968     }
969     int32_t res = DlpCredential::GetInstance().GetMDMPolicy(appIdList);
970     if (appIdList.size() > MAX_APPID_LIST_SIZE) {
971         DLP_LOG_ERROR(LABEL, "appIdList larger than limit");
972         return DLP_SERVICE_ERROR_PARCEL_OPERATE_FAIL;
973     }
974     return res;
975 }
976 
RemoveMDMPolicy()977 int32_t DlpPermissionService::RemoveMDMPolicy()
978 {
979     SetTimer(true);
980     int32_t uid = IPCSkeleton::GetCallingUid();
981     if (uid != EDM_UID) {
982         DLP_LOG_ERROR(LABEL, "invalid caller");
983         return DLP_SERVICE_ERROR_PERMISSION_DENY;
984     }
985     return DlpCredential::GetInstance().RemoveMDMPolicy();
986 }
987 
SetSandboxAppConfig(const std::string & configInfo)988 int32_t DlpPermissionService::SetSandboxAppConfig(const std::string& configInfo)
989 {
990     SetTimer(true);
991     if (configInfo.size() >= OHOS::DistributedKv::Entry::MAX_VALUE_LENGTH) {
992         DLP_LOG_ERROR(LABEL, "configInfo is too long");
993         return DLP_PARSE_ERROR_VALUE_INVALID;
994     }
995     std::string temp = configInfo;
996     return SandboxConfigOperate(temp, SandboxConfigOperationEnum::ADD);
997 }
998 
CleanSandboxAppConfig()999 int32_t DlpPermissionService::CleanSandboxAppConfig()
1000 {
1001     SetTimer(true);
1002 
1003     bool sandboxFlag;
1004     if (PermissionManagerAdapter::CheckSandboxFlagWithService(GetCallingTokenID(), sandboxFlag) != DLP_OK) {
1005         return DLP_SERVICE_ERROR_VALUE_INVALID;
1006     }
1007     if (sandboxFlag) {
1008         DLP_LOG_ERROR(LABEL, "Forbid called by a sandbox app");
1009         return DLP_SERVICE_ERROR_API_NOT_FOR_SANDBOX_ERROR;
1010     }
1011     std::string emptyStr = "";
1012     return SandboxConfigOperate(emptyStr, SandboxConfigOperationEnum::CLEAN);
1013 }
1014 
GetSandboxAppConfig(std::string & configInfo)1015 int32_t DlpPermissionService::GetSandboxAppConfig(std::string& configInfo)
1016 {
1017     SetTimer(true);
1018     return SandboxConfigOperate(configInfo, SandboxConfigOperationEnum::GET);
1019 }
1020 
SetDlpFeature(const uint32_t dlpFeatureInfo,bool & statusSetInfo)1021 int32_t DlpPermissionService::SetDlpFeature(const uint32_t dlpFeatureInfo, bool& statusSetInfo)
1022 {
1023     SetTimer(true);
1024     std::string appId;
1025     if (!PermissionManagerAdapter::CheckPermissionAndGetAppId(appId)) {
1026         return DLP_SERVICE_ERROR_PERMISSION_DENY;
1027     }
1028 
1029     unordered_json featureJson;
1030     featureJson[MDM_BUNDLE_NAME] = appId;
1031     featureJson[MDM_ENABLE_VALUE] = dlpFeatureInfo;
1032 
1033     int32_t res = DlpFeatureInfo::SaveDlpFeatureInfoToFile(featureJson);
1034     DLP_LOG_INFO(LABEL, "SaveDlpFeatureInfoToFile res is: %{public}d", res);
1035     if (res == DLP_OK) {
1036         statusSetInfo = true;
1037     }
1038     return DLP_OK;
1039 }
1040 
IsDLPFeatureProvided(bool & isProvideDLPFeature)1041 int32_t DlpPermissionService::IsDLPFeatureProvided(bool& isProvideDLPFeature)
1042 {
1043     SetTimer(true);
1044     uint32_t dlpFeature = 0;
1045     std::string value = OHOS::system::GetParameter(DLP_ENABLE, "");
1046     if (HcIsFileExist(FEATURE_INFO_DATA_FILE_PATH)) {
1047         DLP_LOG_INFO(LABEL, "feature info file exist");
1048         if (DlpFeatureInfo::GetDlpFeatureInfoFromFile(FEATURE_INFO_DATA_FILE_PATH, dlpFeature) != DLP_OK) {
1049             DLP_LOG_ERROR(LABEL, "GetDlpFeatureInfoFromFile failed");
1050             isProvideDLPFeature = (value == TRUE_VALUE);
1051             return DLP_OK;
1052         }
1053         if (dlpFeature != ENABLE_VALUE_TRUE) {
1054             DLP_LOG_ERROR(LABEL, "DlpFeatureInfo is false");
1055             isProvideDLPFeature = false;
1056             return DLP_OK;
1057         }
1058         isProvideDLPFeature = true;
1059         return DLP_OK;
1060     }
1061     DLP_LOG_DEBUG(LABEL, "feature info file not exist!");
1062     isProvideDLPFeature = (value == TRUE_VALUE);
1063     return DLP_OK;
1064 }
1065 
SandConfigOperateCheck(SandboxConfigOperationEnum operationEnum,std::string & bundleName,int32_t & userId,AccessToken::AccessTokenID & originalTokenId)1066 int32_t DlpPermissionService::SandConfigOperateCheck(SandboxConfigOperationEnum operationEnum, std::string& bundleName,
1067     int32_t& userId, AccessToken::AccessTokenID& originalTokenId)
1068 {
1069     uint32_t tokenId = IPCSkeleton::GetCallingTokenID();
1070     bool result = GetCallerBundleName(tokenId, bundleName);
1071     if (!result) {
1072         return DLP_SERVICE_ERROR_VALUE_INVALID;
1073     }
1074     userId = GetCallingUserId();
1075     if (userId < 0) {
1076         DLP_LOG_ERROR(LABEL, "get userId error");
1077         return DLP_SERVICE_ERROR_VALUE_INVALID;
1078     }
1079     originalTokenId = AccessToken::AccessTokenKit::GetHapTokenID(userId, bundleName, 0);
1080     if (originalTokenId == 0) {
1081         DLP_LOG_ERROR(LABEL, "Get normal tokenId error.");
1082         return DLP_SERVICE_ERROR_VALUE_INVALID;
1083     }
1084     if (operationEnum == ADD && originalTokenId != tokenId) {
1085         int32_t uid = IPCSkeleton::GetCallingUid();
1086         DlpSandboxInfo info;
1087         result = appStateObserver_->GetSandboxInfo(uid, info);
1088         if (!result) {
1089             DLP_LOG_ERROR(LABEL, "Can not found sandbox info, tokenId=%{public}u", tokenId);
1090             return DLP_SERVICE_ERROR_VALUE_INVALID;
1091         }
1092         if (info.hasRead) {
1093             DLP_LOG_ERROR(LABEL, "Sandbox has read dlp file, tokenId=%{public}u", tokenId);
1094             return DLP_SERVICE_ERROR_API_NOT_FOR_SANDBOX_ERROR;
1095         }
1096     }
1097     return DLP_OK;
1098 }
1099 
SandboxConfigOperate(std::string & configInfo,SandboxConfigOperationEnum operationEnum)1100 int32_t DlpPermissionService::SandboxConfigOperate(std::string& configInfo, SandboxConfigOperationEnum operationEnum)
1101 {
1102     std::string callerBundleName;
1103     int32_t userId;
1104     AccessTokenID originalTokenId;
1105     int32_t res = SandConfigOperateCheck(operationEnum, callerBundleName, userId, originalTokenId);
1106     if (res != DLP_OK) {
1107         return res;
1108     }
1109     res = DlpCredential::GetInstance().CheckMdmPermission(callerBundleName, userId);
1110     if (res != DLP_OK) {
1111         return res;
1112     }
1113     switch (operationEnum) {
1114         case ADD:
1115             res = SandboxConfigKvDataStorage::GetInstance().AddSandboxConfigIntoDataStorage(userId, callerBundleName,
1116                 configInfo, std::to_string(originalTokenId));
1117             break;
1118         case GET:
1119             res = SandboxConfigKvDataStorage::GetInstance().GetSandboxConfigFromDataStorage(userId, callerBundleName,
1120                 configInfo, std::to_string(originalTokenId));
1121             break;
1122         case CLEAN:
1123             res = SandboxConfigKvDataStorage::GetInstance().DeleteSandboxConfigFromDataStorage(userId,
1124                 callerBundleName, std::to_string(originalTokenId));
1125             break;
1126         default:
1127             DLP_LOG_ERROR(LABEL, "enter default case");
1128             break;
1129     }
1130     return res;
1131 }
1132 
SetReadFlag(uint32_t uid)1133 int32_t DlpPermissionService::SetReadFlag(uint32_t uid)
1134 {
1135     if (!PermissionManagerAdapter::CheckPermission(PERMISSION_ACCESS_DLP_FILE)) {
1136         return DLP_SERVICE_ERROR_PERMISSION_DENY;
1137     }
1138     DlpSandboxInfo info;
1139     appStateObserver_->GetSandboxInfo(uid, info);
1140     int32_t res = RetentionFileManager::GetInstance().UpdateReadFlag(info.tokenId);
1141     if (res != 0) {
1142         return res;
1143     }
1144     appStateObserver_->UpdatReadFlag(uid);
1145     return DLP_OK;
1146 }
1147 
SetTimer(bool isNeedStartTimer)1148 void DlpPermissionService::SetTimer(bool isNeedStartTimer)
1149 {
1150 #ifndef DLP_FUZZ_TEST
1151     if (isNeedStartTimer) {
1152         DLP_LOG_DEBUG(LABEL, "enter StartTimer");
1153         StartTimer();
1154     }
1155 #endif
1156 }
1157 
Dump(int fd,const std::vector<std::u16string> & args)1158 int DlpPermissionService::Dump(int fd, const std::vector<std::u16string>& args)
1159 {
1160     if (fd < 0) {
1161         return ERR_INVALID_VALUE;
1162     }
1163 
1164     dprintf(fd, "DlpPermission Dump:\n");
1165     std::string arg0 = (args.size() == 0) ? "" : Str16ToStr8(args.at(0));
1166     if (arg0.compare("-h") == 0) {
1167         dprintf(fd, "Usage:\n");
1168         dprintf(fd, "      -h: command help\n");
1169         dprintf(fd, "      -d: default dump\n");
1170     } else if (arg0.compare("-d") == 0 || arg0.compare("") == 0) {
1171         if (appStateObserver_ != nullptr) {
1172             appStateObserver_->DumpSandbox(fd);
1173         } else {
1174             return ERR_INVALID_VALUE;
1175         }
1176     }
1177 
1178     return ERR_OK;
1179 }
1180 } // namespace DlpPermission
1181 } // namespace Security
1182 } // namespace OHOS
1183