• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 #include "sec_comp_manager.h"
16 
17 #include "bundle_mgr_client.h"
18 #include "delay_exit_task.h"
19 #include "display.h"
20 #include "display_info.h"
21 #include "display_manager.h"
22 #include "hisysevent.h"
23 #include "i_sec_comp_service.h"
24 #include "ipc_skeleton.h"
25 #include "iservice_registry.h"
26 #include "sec_comp_enhance_adapter.h"
27 #include "sec_comp_err.h"
28 #include "sec_comp_info.h"
29 #include "sec_comp_info_helper.h"
30 #include "sec_comp_log.h"
31 
32 namespace OHOS {
33 namespace Security {
34 namespace SecurityComponent {
35 namespace {
36 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_SECURITY_COMPONENT, "SecCompManager"};
37 static constexpr int32_t SC_ID_START = 1000;
38 static constexpr int32_t MAX_INT_NUM = 0x7fffffff;
39 static constexpr int32_t MAX_SINGLE_PROC_COMP_SIZE = 500;
40 static constexpr unsigned long REPORT_REMOTE_OBJECT_SIZE = 2UL;
41 }
42 
SecCompManager()43 SecCompManager::SecCompManager()
44 {
45     scIdStart_ = SC_ID_START;
46 }
47 
GetInstance()48 SecCompManager& SecCompManager::GetInstance()
49 {
50     static SecCompManager instance;
51     return instance;
52 }
53 
CreateScId()54 int32_t SecCompManager::CreateScId()
55 {
56     std::lock_guard<std::mutex> lock(scIdMtx_);
57     if (scIdStart_ == MAX_INT_NUM) {
58         scIdStart_ = SC_ID_START;
59     } else {
60         scIdStart_++;
61     }
62     return scIdStart_;
63 }
64 
AddSecurityComponentToList(int32_t pid,AccessToken::AccessTokenID tokenId,std::shared_ptr<SecCompEntity> newEntity)65 int32_t SecCompManager::AddSecurityComponentToList(int32_t pid,
66     AccessToken::AccessTokenID tokenId, std::shared_ptr<SecCompEntity> newEntity)
67 {
68     OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->componentInfoLock_);
69     if (isSaExit_) {
70         SC_LOG_ERROR(LABEL, "SA is exiting, retry...");
71         return SC_SERVICE_ERROR_SERVICE_NOT_EXIST;
72     }
73 
74     auto iter = componentMap_.find(pid);
75     if (iter != componentMap_.end()) {
76         if (iter->second.compList.size() > MAX_SINGLE_PROC_COMP_SIZE) {
77             SC_LOG_ERROR(LABEL, "single proccess has too many component.");
78             return SC_SERVICE_ERROR_VALUE_INVALID;
79         }
80         iter->second.isForeground = true;
81         iter->second.compList.emplace_back(newEntity);
82         SecCompEnhanceAdapter::EnableInputEnhance();
83         DelayExitTask::GetInstance().Stop();
84         return SC_OK;
85     }
86 
87     ProcessCompInfos newProcess;
88     newProcess.isForeground = true;
89     newProcess.tokenId = tokenId;
90     newProcess.compList.emplace_back(newEntity);
91     componentMap_[pid] = newProcess;
92     SecCompEnhanceAdapter::EnableInputEnhance();
93     DelayExitTask::GetInstance().Stop();
94     return SC_OK;
95 }
96 
DeleteSecurityComponentFromList(int32_t pid,int32_t scId)97 int32_t SecCompManager::DeleteSecurityComponentFromList(int32_t pid, int32_t scId)
98 {
99     OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->componentInfoLock_);
100     auto iter = componentMap_.find(pid);
101     if (iter == componentMap_.end()) {
102         SC_LOG_ERROR(LABEL, "Can not find registered process");
103         return SC_SERVICE_ERROR_COMPONENT_NOT_EXIST;
104     }
105     auto& list = iter->second.compList;
106     for (auto it = list.begin(); it != list.end(); ++it) {
107         std::shared_ptr<SecCompEntity> sc = *it;
108         if (sc == nullptr) {
109             SC_LOG_ERROR(LABEL, "Secomp entity is nullptr");
110             continue;
111         }
112         if (sc->scId_ == scId) {
113             list.erase(it);
114             if (!IsForegroundCompExist()) {
115                 SecCompEnhanceAdapter::DisableInputEnhance();
116             }
117             DelayExitTask::GetInstance().Start();
118             return SC_OK;
119         }
120     }
121     SC_LOG_ERROR(LABEL, "Can not find component");
122     return SC_SERVICE_ERROR_COMPONENT_NOT_EXIST;
123 }
124 
TransformCallBackResult(enum SCErrCode error)125 static std::string TransformCallBackResult(enum SCErrCode error)
126 {
127     std::string errMsg = "";
128     switch (error) {
129         case SC_ENHANCE_ERROR_NOT_EXIST_ENHANCE:
130             errMsg = "enhance do not exist";
131             break;
132         case SC_ENHANCE_ERROR_VALUE_INVALID:
133             errMsg = "value is invalid";
134             break;
135         case SC_ENHANCE_ERROR_CALLBACK_NOT_EXIST:
136             errMsg = "callback do not exist";
137             break;
138         case SC_ENHANCE_ERROR_CALLBACK_OPER_FAIL:
139             errMsg = "callback operate fail";
140             break;
141         case SC_SERVICE_ERROR_COMPONENT_INFO_INVALID:
142             errMsg = "component info invalid";
143             break;
144         case SC_ENHANCE_ERROR_CALLBACK_CHECK_FAIL:
145             errMsg = "callback check fail";
146             break;
147         default:
148             errMsg = "unknown error";
149             break;
150     }
151     return errMsg;
152 }
153 
GetSecurityComponentFromList(int32_t pid,int32_t scId)154 std::shared_ptr<SecCompEntity> SecCompManager::GetSecurityComponentFromList(int32_t pid, int32_t scId)
155 {
156     auto iter = componentMap_.find(pid);
157     if (iter == componentMap_.end()) {
158         return nullptr;
159     }
160     auto& list = iter->second.compList;
161     for (auto it = list.begin(); it != list.end(); ++it) {
162         std::shared_ptr<SecCompEntity> sc = *it;
163         if (sc == nullptr) {
164             SC_LOG_ERROR(LABEL, "Secomp entity is nullptr");
165             continue;
166         }
167         if (sc->scId_ == scId) {
168             return *it;
169         }
170     }
171     return nullptr;
172 }
173 
IsForegroundCompExist()174 bool SecCompManager::IsForegroundCompExist()
175 {
176     return std::any_of(componentMap_.begin(), componentMap_.end(), [](const auto & iter) {
177         return (iter.second.isForeground) && (iter.second.compList.size() > 0);
178     });
179 }
180 
IsCompExist()181 bool SecCompManager::IsCompExist()
182 {
183     return std::any_of(componentMap_.begin(), componentMap_.end(), [](const auto & iter) {
184         return (iter.second.compList.size() > 0);
185     });
186 }
187 
NotifyProcessForeground(int32_t pid)188 void SecCompManager::NotifyProcessForeground(int32_t pid)
189 {
190     OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->componentInfoLock_);
191     auto iter = componentMap_.find(pid);
192     if (iter == componentMap_.end()) {
193         return;
194     }
195     SecCompPermManager::GetInstance().CancelAppRevokingPermisions(iter->second.tokenId);
196     iter->second.isForeground = true;
197     if (IsForegroundCompExist()) {
198         SecCompEnhanceAdapter::EnableInputEnhance();
199     }
200 
201     SC_LOG_INFO(LABEL, "App pid %{public}d to foreground", pid);
202 }
203 
NotifyProcessBackground(int32_t pid)204 void SecCompManager::NotifyProcessBackground(int32_t pid)
205 {
206     OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->componentInfoLock_);
207     auto iter = componentMap_.find(pid);
208     if (iter == componentMap_.end()) {
209         return;
210     }
211 
212     SecCompPermManager::GetInstance().RevokeAppPermisionsDelayed(iter->second.tokenId);
213     iter->second.isForeground = false;
214     if (!IsForegroundCompExist()) {
215         SecCompEnhanceAdapter::DisableInputEnhance();
216     }
217     SC_LOG_INFO(LABEL, "App pid %{public}d to background", pid);
218 }
219 
NotifyProcessDied(int32_t pid)220 void SecCompManager::NotifyProcessDied(int32_t pid)
221 {
222     // notify enhance process died.
223     SecCompEnhanceAdapter::NotifyProcessDied(pid);
224 
225     malicious_.RemoveAppFromMaliciousAppList(pid);
226     OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->componentInfoLock_);
227     auto iter = componentMap_.find(pid);
228     if (iter == componentMap_.end()) {
229         return;
230     }
231 
232     FirstUseDialog::GetInstance().RemoveDialogWaitEntitys(pid);
233 
234     SC_LOG_INFO(LABEL, "App pid %{public}d died", pid);
235     iter->second.compList.clear();
236     SecCompPermManager::GetInstance().RevokeAppPermissions(iter->second.tokenId);
237     SecCompPermManager::GetInstance().RevokeTempSavePermission(iter->second.tokenId);
238     componentMap_.erase(pid);
239 
240     if (!IsForegroundCompExist()) {
241         SecCompEnhanceAdapter::DisableInputEnhance();
242     }
243 
244     DelayExitTask::GetInstance().Start();
245 }
246 
ExitSaProcess()247 void SecCompManager::ExitSaProcess()
248 {
249     OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->componentInfoLock_);
250     if (IsCompExist()) {
251         SC_LOG_INFO(LABEL, "Apps using security component still exist, no exit sa");
252         return;
253     }
254 
255     isSaExit_ = true;
256     SecCompEnhanceAdapter::DisableInputEnhance();
257     SecCompEnhanceAdapter::ExitEnhanceService();
258 
259     SC_LOG_INFO(LABEL, "All processes using security component died, start sa exit");
260     auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
261     if (systemAbilityMgr == nullptr) {
262         SC_LOG_ERROR(LABEL, "Failed to get SystemAbilityManager.");
263         return;
264     }
265     int32_t ret = systemAbilityMgr->UnloadSystemAbility(SA_ID_SECURITY_COMPONENT_SERVICE);
266     if (ret != SC_OK) {
267         SC_LOG_ERROR(LABEL, "Failed to UnloadSystemAbility service! errcode=%{public}d", ret);
268         return;
269     }
270     SC_LOG_INFO(LABEL, "UnloadSystemAbility successfully!");
271 }
272 
ExitWhenAppMgrDied()273 void SecCompManager::ExitWhenAppMgrDied()
274 {
275     OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->componentInfoLock_);
276     for (auto iter = componentMap_.begin(); iter != componentMap_.end(); ++iter) {
277         iter->second.compList.clear();
278         SecCompPermManager::GetInstance().RevokeAppPermissions(iter->second.tokenId);
279         SecCompPermManager::GetInstance().RevokeTempSavePermission(iter->second.tokenId);
280     }
281     componentMap_.clear();
282 
283     // no need exit enhance service, only disable input enhance.
284     SecCompEnhanceAdapter::DisableInputEnhance();
285     isSaExit_ = true;
286 
287     SC_LOG_INFO(LABEL, "app mgr died, start sa exit");
288     auto systemAbilityMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
289     if (systemAbilityMgr == nullptr) {
290         SC_LOG_ERROR(LABEL, "failed to get SystemAbilityManager.");
291         return;
292     }
293     int32_t ret = systemAbilityMgr->UnloadSystemAbility(SA_ID_SECURITY_COMPONENT_SERVICE);
294     if (ret != SC_OK) {
295         SC_LOG_ERROR(LABEL, "failed to UnloadSystemAbility service! errcode=%{public}d", ret);
296         return;
297     }
298     SC_LOG_INFO(LABEL, "UnloadSystemAbility successfully!");
299 }
300 
SendCheckInfoEnhanceSysEvent(int32_t scId,SecCompType type,const std::string & scene,int32_t res)301 void SecCompManager::SendCheckInfoEnhanceSysEvent(int32_t scId,
302     SecCompType type, const std::string& scene, int32_t res)
303 {
304     int32_t uid = IPCSkeleton::GetCallingUid();
305     OHOS::AppExecFwk::BundleMgrClient bmsClient;
306     std::string bundleName = "";
307     bmsClient.GetNameForUid(uid, bundleName);
308     if (res == SC_ENHANCE_ERROR_CHALLENGE_CHECK_FAIL) {
309         HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CHALLENGE_CHECK_FAILED",
310             HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", uid, "CALLER_BUNDLE_NAME", bundleName,
311             "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "SC_TYPE", type, "CALL_SCENE",
312             scene);
313     } else {
314         HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CALLBACK_FAILED",
315             HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", uid, "CALLER_BUNDLE_NAME", bundleName,
316             "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_TYPE", type,
317             "CALL_SCENE", scene, "REASON", TransformCallBackResult(static_cast<enum SCErrCode>(res)));
318     }
319 }
320 
AddSecurityComponentProcess(const SecCompCallerInfo & caller)321 int32_t SecCompManager::AddSecurityComponentProcess(const SecCompCallerInfo& caller)
322 {
323     DelayExitTask::GetInstance().Stop();
324     {
325         OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->componentInfoLock_);
326         if (isSaExit_) {
327             SC_LOG_ERROR(LABEL, "SA is exiting, retry...");
328             return SC_SERVICE_ERROR_SERVICE_NOT_EXIST;
329         }
330 
331         auto iter = componentMap_.find(caller.pid);
332         if (iter == componentMap_.end()) {
333             ProcessCompInfos newProcess;
334             newProcess.isForeground = true;
335             newProcess.tokenId = caller.tokenId;
336             componentMap_[caller.pid] = newProcess;
337         }
338         SecCompEnhanceAdapter::EnableInputEnhance();
339     }
340     SecCompEnhanceAdapter::AddSecurityComponentProcess(caller.pid);
341     return SC_OK;
342 }
343 
RegisterSecurityComponent(SecCompType type,const nlohmann::json & jsonComponent,const SecCompCallerInfo & caller,int32_t & scId)344 int32_t SecCompManager::RegisterSecurityComponent(SecCompType type,
345     const nlohmann::json& jsonComponent, const SecCompCallerInfo& caller, int32_t& scId)
346 {
347     SC_LOG_DEBUG(LABEL, "PID: %{public}d, register security component", caller.pid);
348     if (malicious_.IsInMaliciousAppList(caller.pid, caller.uid)) {
349         SC_LOG_ERROR(LABEL, "app is in MaliciousAppList, never allow it");
350         return SC_ENHANCE_ERROR_IN_MALICIOUS_LIST;
351     }
352 
353     SecCompBase* componentPtr = SecCompInfoHelper::ParseComponent(type, jsonComponent);
354     std::shared_ptr<SecCompBase> component(componentPtr);
355     if (component == nullptr) {
356         SC_LOG_ERROR(LABEL, "Parse component info invalid");
357         int32_t uid = IPCSkeleton::GetCallingUid();
358         OHOS::AppExecFwk::BundleMgrClient bmsClient;
359         std::string bundleName = "";
360         bmsClient.GetNameForUid(uid, bundleName);
361         HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "COMPONENT_INFO_CHECK_FAILED",
362             HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", uid, "CALLER_BUNDLE_NAME", bundleName,
363             "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "CALL_SCENE", "REGITSTER", "SC_TYPE", type);
364         return SC_SERVICE_ERROR_COMPONENT_INFO_INVALID;
365     }
366 
367     int32_t enhanceRes =
368         SecCompEnhanceAdapter::CheckComponentInfoEnhance(caller.pid, component, jsonComponent);
369     if (enhanceRes != SC_OK) {
370         SendCheckInfoEnhanceSysEvent(INVALID_SC_ID, type, "REGISTER", enhanceRes);
371         SC_LOG_ERROR(LABEL, "enhance check failed");
372         malicious_.AddAppToMaliciousAppList(caller.pid);
373         return enhanceRes;
374     }
375 
376     int32_t registerId = CreateScId();
377     std::shared_ptr<SecCompEntity> entity =
378         std::make_shared<SecCompEntity>(component, caller.tokenId, registerId, caller.pid, caller.uid);
379     int32_t ret = AddSecurityComponentToList(caller.pid, caller.tokenId, entity);
380     if (ret == SC_OK) {
381         scId = registerId;
382     } else {
383         SC_LOG_ERROR(LABEL, "Register security component failed");
384         scId = INVALID_SC_ID;
385     }
386     return ret;
387 }
388 
UpdateSecurityComponent(int32_t scId,const nlohmann::json & jsonComponent,const SecCompCallerInfo & caller)389 int32_t SecCompManager::UpdateSecurityComponent(int32_t scId, const nlohmann::json& jsonComponent,
390     const SecCompCallerInfo& caller)
391 {
392     SC_LOG_DEBUG(LABEL, "PID: %{public}d, update security component", caller.pid);
393     if (malicious_.IsInMaliciousAppList(caller.pid, caller.uid)) {
394         SC_LOG_ERROR(LABEL, "app is in MaliciousAppList, never allow it");
395         return SC_ENHANCE_ERROR_IN_MALICIOUS_LIST;
396     }
397 
398     OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->componentInfoLock_);
399     std::shared_ptr<SecCompEntity> sc = GetSecurityComponentFromList(caller.pid, scId);
400     if (sc == nullptr) {
401         SC_LOG_ERROR(LABEL, "Can not find target component");
402         return SC_SERVICE_ERROR_COMPONENT_NOT_EXIST;
403     }
404     SecCompBase* report = SecCompInfoHelper::ParseComponent(sc->GetType(), jsonComponent);
405     std::shared_ptr<SecCompBase> reportComponentInfo(report);
406     if (reportComponentInfo == nullptr) {
407         SC_LOG_ERROR(LABEL, "Update component info invalid");
408         int32_t uid = IPCSkeleton::GetCallingUid();
409         OHOS::AppExecFwk::BundleMgrClient bmsClient;
410         std::string bundleName = "";
411         bmsClient.GetNameForUid(uid, bundleName);
412         HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "COMPONENT_INFO_CHECK_FAILED",
413             HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", uid, "CALLER_BUNDLE_NAME", bundleName,
414             "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "CALL_SCENE", "UPDATE",
415             "SC_TYPE", sc->GetType());
416         return SC_SERVICE_ERROR_COMPONENT_INFO_INVALID;
417     }
418 
419     int32_t enhanceRes =
420         SecCompEnhanceAdapter::CheckComponentInfoEnhance(caller.pid, reportComponentInfo, jsonComponent);
421     if (enhanceRes != SC_OK) {
422         SendCheckInfoEnhanceSysEvent(scId, sc->GetType(), "UPDATE", enhanceRes);
423         SC_LOG_ERROR(LABEL, "enhance check failed");
424         malicious_.AddAppToMaliciousAppList(caller.pid);
425         return enhanceRes;
426     }
427 
428     sc->componentInfo_ = reportComponentInfo;
429     return SC_OK;
430 }
431 
UnregisterSecurityComponent(int32_t scId,const SecCompCallerInfo & caller)432 int32_t SecCompManager::UnregisterSecurityComponent(int32_t scId, const SecCompCallerInfo& caller)
433 {
434     SC_LOG_DEBUG(LABEL, "PID: %{public}d, unregister security component", caller.pid);
435     if (scId < 0) {
436         SC_LOG_ERROR(LABEL, "ScId is invalid");
437         return SC_SERVICE_ERROR_VALUE_INVALID;
438     }
439     return DeleteSecurityComponentFromList(caller.pid, scId);
440 }
441 
CheckClickSecurityComponentInfo(std::shared_ptr<SecCompEntity> sc,int32_t scId,const nlohmann::json & jsonComponent,const SecCompCallerInfo & caller)442 int32_t SecCompManager::CheckClickSecurityComponentInfo(std::shared_ptr<SecCompEntity> sc, int32_t scId,
443     const nlohmann::json& jsonComponent, const SecCompCallerInfo& caller)
444 {
445     SC_LOG_DEBUG(LABEL, "PID: %{public}d, Check security component", caller.pid);
446     SecCompBase* report = SecCompInfoHelper::ParseComponent(sc->GetType(), jsonComponent);
447     std::shared_ptr<SecCompBase> reportComponentInfo(report);
448     int32_t uid = IPCSkeleton::GetCallingUid();
449     OHOS::AppExecFwk::BundleMgrClient bmsClient;
450     std::string bundleName = "";
451     bmsClient.GetNameForUid(uid, bundleName);
452     if ((reportComponentInfo == nullptr) || (!reportComponentInfo->GetValid())) {
453         SC_LOG_ERROR(LABEL, "report component info invalid");
454         HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "COMPONENT_INFO_CHECK_FAILED",
455             HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", uid, "CALLER_BUNDLE_NAME", bundleName,
456             "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "CALL_SCENE", "CLICK", "SC_TYPE",
457             sc->GetType());
458         return SC_SERVICE_ERROR_COMPONENT_INFO_INVALID;
459     }
460     if (report && (report->isClipped_)) {
461         HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "CLIP_CHECK_FAILED",
462             HiviewDFX::HiSysEvent::EventType::SECURITY,
463             "CALLER_BUNDLE_NAME", bundleName, "COMPONENT_INFO", jsonComponent.dump().c_str());
464     }
465 
466     if ((!SecCompInfoHelper::CheckRectValid(reportComponentInfo->rect_, reportComponentInfo->windowRect_,
467         report->displayId_, report->crossAxisState_))) {
468         SC_LOG_ERROR(LABEL, "compare component info failed.");
469         HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "COMPONENT_INFO_CHECK_FAILED",
470             HiviewDFX::HiSysEvent::EventType::SECURITY, "CALLER_UID", uid, "CALLER_BUNDLE_NAME", bundleName,
471             "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "CALL_SCENE", "CLICK", "SC_TYPE",
472             sc->GetType());
473         return SC_SERVICE_ERROR_COMPONENT_INFO_INVALID;
474     }
475     int32_t enhanceRes =
476         SecCompEnhanceAdapter::CheckComponentInfoEnhance(caller.pid, reportComponentInfo, jsonComponent);
477     if (enhanceRes != SC_OK) {
478         SendCheckInfoEnhanceSysEvent(scId, sc->GetType(), "CLICK", enhanceRes);
479         SC_LOG_ERROR(LABEL, "enhance check failed");
480         malicious_.AddAppToMaliciousAppList(caller.pid);
481         return enhanceRes;
482     }
483 
484     sc->componentInfo_ = reportComponentInfo;
485     return SC_OK;
486 }
487 
ReportEvent(std::string eventName,HiviewDFX::HiSysEvent::EventType eventType,int32_t scId,SecCompType scType)488 static void ReportEvent(std::string eventName, HiviewDFX::HiSysEvent::EventType eventType, int32_t scId,
489     SecCompType scType)
490 {
491     int32_t uid = IPCSkeleton::GetCallingUid();
492     OHOS::AppExecFwk::BundleMgrClient bmsClient;
493     std::string bundleName = "";
494     bmsClient.GetNameForUid(uid, bundleName);
495     HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, eventName,
496         eventType, "CALLER_UID", uid, "CALLER_BUNDLE_NAME", bundleName,
497         "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "SC_TYPE", scType);
498 }
499 
GetFoldOffsetY(const CrossAxisState crossAxisState)500 void SecCompManager::GetFoldOffsetY(const CrossAxisState crossAxisState)
501 {
502     if (crossAxisState == CrossAxisState::STATE_INVALID) {
503         return;
504     }
505     if (superFoldOffsetY_ != 0) {
506         return;
507     }
508     auto foldCreaseRegion = OHOS::Rosen::DisplayManager::GetInstance().GetCurrentFoldCreaseRegion();
509     if (foldCreaseRegion == nullptr) {
510         SC_LOG_ERROR(LABEL, "foldCreaseRegion is nullptr");
511         return;
512     }
513     const auto& creaseRects = foldCreaseRegion->GetCreaseRects();
514     if (creaseRects.empty()) {
515         SC_LOG_ERROR(LABEL, "creaseRects is empty");
516         return;
517     }
518     const auto& rect = creaseRects.front();
519     superFoldOffsetY_ = rect.height_ + rect.posY_;
520     SC_LOG_INFO(LABEL, "height: %{public}d, posY: %{public}d", rect.height_, rect.posY_);
521 }
522 
ReportSecurityComponentClickEvent(int32_t scId,const nlohmann::json & compJson,const SecCompCallerInfo & caller,SecCompClickEvent & clickInfo,const std::vector<sptr<IRemoteObject>> & remote)523 int32_t SecCompManager::ReportSecurityComponentClickEvent(int32_t scId, const nlohmann::json& compJson,
524     const SecCompCallerInfo& caller, SecCompClickEvent& clickInfo, const std::vector<sptr<IRemoteObject>>& remote)
525 {
526     if (remote.size() < REPORT_REMOTE_OBJECT_SIZE) {
527         return SC_SERVICE_ERROR_VALUE_INVALID;
528     }
529 
530     if (malicious_.IsInMaliciousAppList(caller.pid, caller.uid)) {
531         SC_LOG_ERROR(LABEL, "app is in MaliciousAppList, never allow it");
532         return SC_ENHANCE_ERROR_IN_MALICIOUS_LIST;
533     }
534 
535     OHOS::Utils::UniqueReadGuard<OHOS::Utils::RWLock> lk(this->componentInfoLock_);
536     std::shared_ptr<SecCompEntity> sc = GetSecurityComponentFromList(caller.pid, scId);
537     if (sc == nullptr) {
538         SC_LOG_ERROR(LABEL, "Can not find target component");
539         return SC_SERVICE_ERROR_COMPONENT_NOT_EXIST;
540     }
541 
542     int32_t res = CheckClickSecurityComponentInfo(sc, scId, compJson, caller);
543     if (res != SC_OK) {
544         return res;
545     }
546     SecCompBase* report = SecCompInfoHelper::ParseComponent(sc->GetType(), compJson);
547     if (report == nullptr) {
548         return SC_SERVICE_ERROR_COMPONENT_INFO_INVALID;
549     }
550 
551     GetFoldOffsetY(report->crossAxisState_);
552 
553     res = sc->CheckClickInfo(clickInfo, superFoldOffsetY_, report->crossAxisState_);
554     if (res != SC_OK) {
555         ReportEvent("CLICK_INFO_CHECK_FAILED", HiviewDFX::HiSysEvent::EventType::SECURITY,
556             scId, sc->GetType());
557         if (res == SC_ENHANCE_ERROR_CLICK_EXTRA_CHECK_FAIL) {
558             malicious_.AddAppToMaliciousAppList(caller.pid);
559         }
560 
561         return SC_SERVICE_ERROR_CLICK_EVENT_INVALID;
562     }
563 
564     if (FirstUseDialog::GetInstance().NotifyFirstUseDialog(sc, remote[0], remote[1], report->displayId_,
565         report->crossAxisState_) == SC_SERVICE_ERROR_WAIT_FOR_DIALOG_CLOSE) {
566         SC_LOG_INFO(LABEL, "start dialog, onclick will be trap after dialog closed.");
567         return SC_SERVICE_ERROR_WAIT_FOR_DIALOG_CLOSE;
568     }
569 
570     res = sc->GrantTempPermission();
571     if (res != SC_OK) {
572         ReportEvent("TEMP_GRANT_FAILED", HiviewDFX::HiSysEvent::EventType::FAULT,
573             scId, sc->GetType());
574         return res;
575     }
576     HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::SEC_COMPONENT, "TEMP_GRANT_SUCCESS",
577         HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "CALLER_UID", IPCSkeleton::GetCallingUid(),
578         "CALLER_PID", IPCSkeleton::GetCallingPid(), "SC_ID", scId, "SC_TYPE", sc->GetType());
579     return res;
580 }
581 
DumpSecComp(std::string & dumpStr)582 void SecCompManager::DumpSecComp(std::string& dumpStr)
583 {
584     OHOS::Utils::UniqueReadGuard<OHOS::Utils::RWLock> lk(this->componentInfoLock_);
585     for (auto iter = componentMap_.begin(); iter != componentMap_.end(); ++iter) {
586         AccessToken::AccessTokenID tokenId = iter->second.tokenId;
587         bool locationPerm = SecCompPermManager::GetInstance().VerifyPermission(tokenId, LOCATION_COMPONENT);
588         bool pastePerm = SecCompPermManager::GetInstance().VerifyPermission(tokenId, PASTE_COMPONENT);
589         bool savePerm = SecCompPermManager::GetInstance().VerifyPermission(tokenId, SAVE_COMPONENT);
590         dumpStr.append("pid:" + std::to_string(iter->first) + ", tokenId:" + std::to_string(pastePerm) +
591             ", locationPerm:" + std::to_string(locationPerm) + ", pastePerm:" + std::to_string(pastePerm) +
592             ", savePerm:" + std::to_string(savePerm) + " \n");
593         for (auto compIter = iter->second.compList.begin(); compIter != iter->second.compList.end(); ++compIter) {
594             nlohmann::json json;
595             std::shared_ptr<SecCompEntity> sc = *compIter;
596             if (sc == nullptr || sc->componentInfo_ == nullptr) {
597                 continue;
598             }
599 
600             sc->componentInfo_->ToJson(json);
601             dumpStr.append("    scId:" + std::to_string(sc->scId_) +
602                 ", isGrant:" + std::to_string(sc->IsGrant()) + ", " + json.dump() + "\n");
603         }
604     }
605 }
606 
Initialize()607 bool SecCompManager::Initialize()
608 {
609     SC_LOG_DEBUG(LABEL, "Initialize!!");
610     SecCompEnhanceAdapter::StartEnhanceService();
611 
612     secRunner_ = AppExecFwk::EventRunner::Create(true, AppExecFwk::ThreadMode::FFRT);
613     if (!secRunner_) {
614         SC_LOG_ERROR(LABEL, "failed to create a recvRunner.");
615         return false;
616     }
617 
618     secHandler_ = std::make_shared<SecEventHandler>(secRunner_);
619     exitSaProcessFunc_ = []() {
620         SecCompManager::GetInstance().ExitSaProcess();
621     };
622     DelayExitTask::GetInstance().Init(secHandler_, exitSaProcessFunc_);
623     FirstUseDialog::GetInstance().Init(secHandler_);
624     SecCompEnhanceAdapter::EnableInputEnhance();
625     SecCompPermManager::GetInstance().InitEventHandler(secHandler_);
626     DelayExitTask::GetInstance().Start();
627 
628     return true;
629 }
630 }  // namespace SecurityComponent
631 }  // namespace Security
632 }  // namespace OHOS
633