• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-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 "user_auth_service.h"
17 #include "hisysevent_adapter.h"
18 
19 #include <cinttypes>
20 
21 #include "accesstoken_kit.h"
22 #include "auth_common.h"
23 #include "auth_event_listener_manager.h"
24 #include "auth_widget_helper.h"
25 #include "context_factory.h"
26 #include "auth_common.h"
27 #include "context_helper.h"
28 #include "hdi_wrapper.h"
29 #include "iam_check.h"
30 #include "iam_common_defines.h"
31 #include "iam_logger.h"
32 #include "iam_para2str.h"
33 #include "iam_ptr.h"
34 #include "iam_time.h"
35 #include "ipc_common.h"
36 #include "ipc_skeleton.h"
37 #include "keyguard_status_listener.h"
38 #include "system_param_manager.h"
39 #include "soft_bus_manager.h"
40 #include "widget_client.h"
41 #include "remote_msg_util.h"
42 #include "remote_iam_callback.h"
43 #include "remote_auth_service.h"
44 #include "device_manager_util.h"
45 #include "xcollie_helper.h"
46 
47 #define LOG_TAG "USER_AUTH_SA"
48 
49 namespace OHOS {
50 namespace UserIam {
51 namespace UserAuth {
52 namespace {
53 const int32_t MINIMUM_VERSION = 0;
54 const int32_t CURRENT_VERSION = 1;
55 const int32_t USERIAM_IPC_THREAD_NUM = 4;
56 const uint32_t MAX_AUTH_TYPE_SIZE = 3;
57 const uint32_t NETWORK_ID_LENGTH = 64;
58 const bool REMOTE_AUTH_SERVICE_RESULT = RemoteAuthService::GetInstance().Start();
GetTemplatesByAuthType(int32_t userId,AuthType authType,std::vector<uint64_t> & templateIds)59 int32_t GetTemplatesByAuthType(int32_t userId, AuthType authType, std::vector<uint64_t> &templateIds)
60 {
61     templateIds.clear();
62     std::vector<std::shared_ptr<CredentialInfoInterface>> credentialInfos;
63     int32_t ret = UserIdmDatabase::Instance().GetCredentialInfo(userId, authType, credentialInfos);
64     if (ret != SUCCESS) {
65         IAM_LOGE("get credential fail, ret:%{public}d, userId:%{public}d, authType:%{public}d", ret,
66             userId, authType);
67         return GENERAL_ERROR;
68     }
69 
70     if (credentialInfos.empty()) {
71         IAM_LOGE("user %{public}d has no credential type %{public}d", userId, authType);
72         return SUCCESS;
73     }
74 
75     templateIds.reserve(credentialInfos.size());
76     for (auto &info : credentialInfos) {
77         if (info == nullptr) {
78             IAM_LOGE("info is nullptr");
79             continue;
80         }
81         templateIds.push_back(info->GetTemplateId());
82     }
83 
84     return SUCCESS;
85 }
86 
IsTemplateIdListRequired(const std::vector<Attributes::AttributeKey> & keys)87 bool IsTemplateIdListRequired(const std::vector<Attributes::AttributeKey> &keys)
88 {
89     for (const auto &key : keys) {
90         if (key == Attributes::AttributeKey::ATTR_PIN_SUB_TYPE ||
91             key == Attributes::AttributeKey::ATTR_REMAIN_TIMES ||
92             key == Attributes::AttributeKey::ATTR_FREEZING_TIME ||
93             key == Attributes::AttributeKey::ATTR_NEXT_FAIL_LOCKOUT_DURATION) {
94             return true;
95         }
96     }
97     return false;
98 }
99 
GetResourceNodeByTypeAndRole(AuthType authType,ExecutorRole role,std::vector<std::weak_ptr<ResourceNode>> & authTypeNodes)100 void GetResourceNodeByTypeAndRole(AuthType authType, ExecutorRole role,
101     std::vector<std::weak_ptr<ResourceNode>> &authTypeNodes)
102 {
103     authTypeNodes.clear();
104     ResourceNodePool::Instance().Enumerate(
105         [&authTypeNodes, role, authType](const std::weak_ptr<ResourceNode> &weakNode) {
106             auto node = weakNode.lock();
107             if (node == nullptr) {
108                 return;
109             }
110             if (node->GetAuthType() != authType) {
111                 return;
112             }
113             if (node->GetExecutorRole() != role) {
114                 return;
115             }
116             authTypeNodes.push_back(node);
117         });
118 }
119 
GetAuthParamStr(const AuthParamInner & authParam,std::optional<RemoteAuthParam> & remoteAuthParam)120 std::string GetAuthParamStr(const AuthParamInner &authParam, std::optional<RemoteAuthParam> &remoteAuthParam)
121 {
122     std::ostringstream authParamString;
123     authParamString << "userId:" << authParam.userId << " authType:" << authParam.authType
124                     << " atl:" << authParam.authTrustLevel;
125     if (remoteAuthParam.has_value()) {
126         const uint32_t NETWORK_ID_PRINT_LEN = 4;
127         const uint32_t TOKEN_ID_MIN_LEN = 2;
128         auto verifierNetworkIdStr = remoteAuthParam->verifierNetworkId.value_or("").substr(0, NETWORK_ID_PRINT_LEN);
129         auto collectorNetworkIdStr = remoteAuthParam->collectorNetworkId.value_or("").substr(0, NETWORK_ID_PRINT_LEN);
130         auto tokenIdStr = std::to_string(remoteAuthParam->collectorTokenId.value_or(0));
131         if (tokenIdStr.size() > TOKEN_ID_MIN_LEN) {
132             tokenIdStr = std::string(1, tokenIdStr[0]) + "****" + std::string(1, tokenIdStr[tokenIdStr.size() - 1]);
133         } else {
134             tokenIdStr = "";
135         }
136 
137         authParamString << " isRemoteAuth:true" << " verifierNetworkId:" << verifierNetworkIdStr << "****"
138             " collectorNetworkId:" << collectorNetworkIdStr << "****" << " collectorTokenId:" << tokenIdStr;
139     }
140     return authParamString.str();
141 }
142 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(UserAuthService::GetInstance().get());
143 } // namespace
144 std::mutex UserAuthService::mutex_;
145 std::shared_ptr<UserAuthService> UserAuthService::instance_ = nullptr;
146 
GetInstance()147 std::shared_ptr<UserAuthService> UserAuthService::GetInstance()
148 {
149     if (instance_ == nullptr) {
150         std::lock_guard<std::mutex> guard(mutex_);
151         if (instance_ == nullptr) {
152             instance_ = Common::MakeShared<UserAuthService>();
153             if (instance_ == nullptr) {
154                 IAM_LOGE("make share failed");
155             }
156         }
157     }
158     return instance_;
159 }
160 
UserAuthService()161 UserAuthService::UserAuthService()
162     : SystemAbility(SUBSYS_USERIAM_SYS_ABILITY_USERAUTH, true)
163 {}
164 
OnStart()165 void UserAuthService::OnStart()
166 {
167     IAM_LOGI("start service");
168     IPCSkeleton::SetMaxWorkThreadNum(USERIAM_IPC_THREAD_NUM);
169     if (!Publish(this)) {
170         IAM_LOGE("failed to publish service");
171     }
172     SystemParamManager::GetInstance().Start();
173     SoftBusManager::GetInstance().Start();
174     KeyguardStatusListenerManager::GetInstance().RegisterCommonEventListener();
175 }
176 
OnStop()177 void UserAuthService::OnStop()
178 {
179     IAM_LOGI("stop service");
180     SoftBusManager::GetInstance().Stop();
181     KeyguardStatusListenerManager::GetInstance().UnRegisterCommonEventListener();
182 }
183 
CheckAuthTrustLevel(AuthTrustLevel authTrustLevel)184 bool UserAuthService::CheckAuthTrustLevel(AuthTrustLevel authTrustLevel)
185 {
186     if ((authTrustLevel != ATL1) && (authTrustLevel != ATL2) &&
187         (authTrustLevel != ATL3) && (authTrustLevel != ATL4)) {
188         IAM_LOGE("authTrustLevel not support %{public}u", authTrustLevel);
189         return false;
190     }
191     return true;
192 }
193 
GetAvailableStatus(int32_t apiVersion,int32_t userId,AuthType authType,AuthTrustLevel authTrustLevel)194 int32_t UserAuthService::GetAvailableStatus(int32_t apiVersion, int32_t userId, AuthType authType,
195     AuthTrustLevel authTrustLevel)
196 {
197     IAM_LOGI("start with userId");
198 
199     if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
200         IAM_LOGE("failed to check permission");
201         return CHECK_PERMISSION_FAILED;
202     }
203     return GetAvailableStatusInner(apiVersion, userId, authType, authTrustLevel);
204 }
205 
GetAvailableStatus(int32_t apiVersion,AuthType authType,AuthTrustLevel authTrustLevel)206 int32_t UserAuthService::GetAvailableStatus(int32_t apiVersion, AuthType authType, AuthTrustLevel authTrustLevel)
207 {
208     IAM_LOGI("start without userId");
209 
210     if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION) &&
211         !IpcCommon::CheckPermission(*this, ACCESS_BIOMETRIC_PERMISSION)) {
212         IAM_LOGE("failed to check permission");
213         return CHECK_PERMISSION_FAILED;
214     }
215     if ((apiVersion <= API_VERSION_8 && authType == PIN) ||
216         !SystemParamManager::GetInstance().IsAuthTypeEnable(authType)) {
217         IAM_LOGE("authType not support");
218         return TYPE_NOT_SUPPORT;
219     }
220     int32_t userId = INVALID_USER_ID;
221     if (IpcCommon::GetCallingUserId(*this, userId) != SUCCESS) {
222         IAM_LOGE("failed to get userId");
223         return GENERAL_ERROR;
224     }
225     return GetAvailableStatusInner(apiVersion, userId, authType, authTrustLevel);
226 }
227 
GetAvailableStatusInner(int32_t apiVersion,int32_t userId,AuthType authType,AuthTrustLevel authTrustLevel)228 int32_t UserAuthService::GetAvailableStatusInner(int32_t apiVersion, int32_t userId, AuthType authType,
229     AuthTrustLevel authTrustLevel)
230 {
231     if (!CheckAuthTrustLevel(authTrustLevel)) {
232         IAM_LOGE("authTrustLevel is not in correct range");
233         return TRUST_LEVEL_NOT_SUPPORT;
234     }
235     auto hdi = HdiWrapper::GetHdiInstance();
236     if (hdi == nullptr) {
237         IAM_LOGE("hdi interface is nullptr");
238         return GENERAL_ERROR;
239     }
240     int32_t checkRet = GENERAL_ERROR;
241     int32_t result = hdi->GetAvailableStatus(userId, authType, authTrustLevel, checkRet);
242     if (result != SUCCESS) {
243         IAM_LOGE("hdi GetAvailableStatus failed");
244         return GENERAL_ERROR;
245     }
246     IAM_LOGI("GetAvailableStatus result:%{public}d", checkRet);
247     return checkRet;
248 }
249 
FillGetPropertyKeys(AuthType authType,const std::vector<Attributes::AttributeKey> & keys,std::vector<uint32_t> & uint32Keys)250 void UserAuthService::FillGetPropertyKeys(AuthType authType, const std::vector<Attributes::AttributeKey> &keys,
251     std::vector<uint32_t> &uint32Keys)
252 {
253     uint32Keys.reserve(keys.size());
254     for (const auto &key : keys) {
255         if (key == Attributes::ATTR_NEXT_FAIL_LOCKOUT_DURATION && authType != PIN) {
256             continue;
257         }
258         uint32Keys.push_back(static_cast<uint32_t>(key));
259     }
260 }
261 
FillGetPropertyValue(AuthType authType,const std::vector<Attributes::AttributeKey> & keys,Attributes & values)262 void UserAuthService::FillGetPropertyValue(AuthType authType, const std::vector<Attributes::AttributeKey> &keys,
263     Attributes &values)
264 {
265     for (const auto &key : keys) {
266         if (key == Attributes::ATTR_NEXT_FAIL_LOCKOUT_DURATION && authType != PIN) {
267             if (!values.SetInt32Value(Attributes::ATTR_NEXT_FAIL_LOCKOUT_DURATION, FIRST_LOCKOUT_DURATION_EXCEPT_PIN)) {
268                 IAM_LOGE("set nextFailLockoutDuration failed, authType %{public}d", authType);
269             }
270             break;
271         }
272     }
273 }
274 
GetResourseNode(AuthType authType)275 std::shared_ptr<ResourceNode> UserAuthService::GetResourseNode(AuthType authType)
276 {
277     std::vector<std::weak_ptr<ResourceNode>> authTypeNodes;
278     GetResourceNodeByTypeAndRole(authType, ALL_IN_ONE, authTypeNodes);
279     if (authTypeNodes.size() != 1) {
280         IAM_LOGE("auth type %{public}d resource node num %{public}zu is not expected",
281             authType, authTypeNodes.size());
282         return nullptr;
283     }
284 
285     auto resourceNode = authTypeNodes[0].lock();
286     if (resourceNode == nullptr) {
287         IAM_LOGE("resourceNode is nullptr");
288         return nullptr;
289     }
290 
291     return resourceNode;
292 }
293 
GetProperty(int32_t userId,AuthType authType,const std::vector<Attributes::AttributeKey> & keys,sptr<GetExecutorPropertyCallbackInterface> & callback)294 void UserAuthService::GetProperty(int32_t userId, AuthType authType,
295     const std::vector<Attributes::AttributeKey> &keys, sptr<GetExecutorPropertyCallbackInterface> &callback)
296 {
297     IAM_LOGI("start");
298     Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
299     IF_FALSE_LOGE_AND_RETURN(callback != nullptr);
300     Attributes values;
301 
302     if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
303         IAM_LOGE("failed to check permission");
304         callback->OnGetExecutorPropertyResult(CHECK_PERMISSION_FAILED, values);
305         return;
306     }
307 
308     std::vector<uint64_t> templateIds;
309     if (IsTemplateIdListRequired(keys)) {
310         int32_t ret = GetTemplatesByAuthType(userId, authType, templateIds);
311         if (ret != SUCCESS) {
312             IAM_LOGE("get templates fail, ret:%{public}d, userId:%{public}d, authType:%{public}d", ret,
313                 userId, authType);
314             callback->OnGetExecutorPropertyResult(GENERAL_ERROR, values);
315             return;
316         }
317         if (templateIds.size() == 0) {
318             IAM_LOGE("template id list is required, but templateIds size is 0");
319             callback->OnGetExecutorPropertyResult(NOT_ENROLLED, values);
320             return;
321         }
322     }
323 
324     auto resourceNode = GetResourseNode(authType);
325     if (resourceNode == nullptr) {
326         IAM_LOGE("resourceNode is nullptr");
327         callback->OnGetExecutorPropertyResult(GENERAL_ERROR, values);
328         return;
329     }
330 
331     std::vector<uint32_t> uint32Keys;
332     FillGetPropertyKeys(authType, keys, uint32Keys);
333     Attributes attr;
334     attr.SetUint32Value(Attributes::ATTR_PROPERTY_MODE, PROPERTY_MODE_GET);
335     attr.SetUint64ArrayValue(Attributes::ATTR_TEMPLATE_ID_LIST, templateIds);
336     attr.SetUint32ArrayValue(Attributes::ATTR_KEY_LIST, uint32Keys);
337 
338     int32_t result = resourceNode->GetProperty(attr, values);
339     if (result != SUCCESS) {
340         IAM_LOGE("failed to get property, result = %{public}d", result);
341     }
342     FillGetPropertyValue(authType, keys, values);
343 
344     callback->OnGetExecutorPropertyResult(result, values);
345 }
346 
SetProperty(int32_t userId,AuthType authType,const Attributes & attributes,sptr<SetExecutorPropertyCallbackInterface> & callback)347 void UserAuthService::SetProperty(int32_t userId, AuthType authType, const Attributes &attributes,
348     sptr<SetExecutorPropertyCallbackInterface> &callback)
349 {
350     IAM_LOGI("start");
351     Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
352     if (callback == nullptr) {
353         IAM_LOGE("callback is nullptr");
354         return;
355     }
356     if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
357         IAM_LOGE("permission check failed");
358         callback->OnSetExecutorPropertyResult(CHECK_PERMISSION_FAILED);
359         return;
360     }
361 
362     std::vector<std::weak_ptr<ResourceNode>> authTypeNodes;
363     GetResourceNodeByTypeAndRole(authType, ALL_IN_ONE, authTypeNodes);
364     if (authTypeNodes.size() != 1) {
365         IAM_LOGE("auth type %{public}d resource node num %{public}zu is not expected",
366             authType, authTypeNodes.size());
367         callback->OnSetExecutorPropertyResult(GENERAL_ERROR);
368         return;
369     }
370 
371     auto resourceNode = authTypeNodes[0].lock();
372     if (resourceNode == nullptr) {
373         IAM_LOGE("resourceNode is nullptr");
374         callback->OnSetExecutorPropertyResult(GENERAL_ERROR);
375         return;
376     }
377     int32_t result = resourceNode->SetProperty(attributes);
378     if (result != SUCCESS) {
379         IAM_LOGE("set property failed, result = %{public}d", result);
380     }
381     callback->OnSetExecutorPropertyResult(result);
382 }
383 
GetAuthContextCallback(int32_t apiVersion,const std::vector<uint8_t> & challenge,AuthType authType,AuthTrustLevel authTrustLevel,sptr<UserAuthCallbackInterface> & callback)384 std::shared_ptr<ContextCallback> UserAuthService::GetAuthContextCallback(int32_t apiVersion,
385     const std::vector<uint8_t> &challenge, AuthType authType,
386     AuthTrustLevel authTrustLevel, sptr<UserAuthCallbackInterface> &callback)
387 {
388     if (callback == nullptr) {
389         IAM_LOGE("callback is nullptr");
390         return nullptr;
391     }
392     auto contextCallback = ContextCallback::NewInstance(callback, TRACE_AUTH_USER_ALL);
393     if (contextCallback == nullptr) {
394         IAM_LOGE("failed to construct context callback");
395         Attributes extraInfo;
396         callback->OnResult(GENERAL_ERROR, extraInfo);
397         return nullptr;
398     }
399     contextCallback->SetTraceAuthType(authType);
400     contextCallback->SetTraceAuthTrustLevel(authTrustLevel);
401     contextCallback->SetTraceAuthWidgetType(authType);
402     contextCallback->SetTraceSdkVersion(apiVersion);
403     return contextCallback;
404 }
405 
CheckAuthPermissionAndParam(int32_t authType,const int32_t & callerType,const std::string & callerName,AuthTrustLevel authTrustLevel)406 int32_t UserAuthService::CheckAuthPermissionAndParam(int32_t authType, const int32_t &callerType,
407     const std::string &callerName, AuthTrustLevel authTrustLevel)
408 {
409     if (!IpcCommon::CheckPermission(*this, ACCESS_BIOMETRIC_PERMISSION)) {
410         IAM_LOGE("failed to check permission");
411         return CHECK_PERMISSION_FAILED;
412     }
413     if (callerType == Security::AccessToken::TOKEN_HAP && (!IpcCommon::CheckForegroundApplication(callerName))) {
414         IAM_LOGE("failed to check foreground application");
415         return CHECK_PERMISSION_FAILED;
416     }
417     if ((authType == PIN) || !SystemParamManager::GetInstance().IsAuthTypeEnable(authType)) {
418         IAM_LOGE("authType not support");
419         return TYPE_NOT_SUPPORT;
420     }
421     if (!CheckAuthTrustLevel(authTrustLevel)) {
422         IAM_LOGE("authTrustLevel is not in correct range");
423         return TRUST_LEVEL_NOT_SUPPORT;
424     }
425     return SUCCESS;
426 }
427 
Auth(int32_t apiVersion,const std::vector<uint8_t> & challenge,AuthType authType,AuthTrustLevel authTrustLevel,sptr<UserAuthCallbackInterface> & callback)428 uint64_t UserAuthService::Auth(int32_t apiVersion, const std::vector<uint8_t> &challenge,
429     AuthType authType, AuthTrustLevel authTrustLevel, sptr<UserAuthCallbackInterface> &callback)
430 {
431     IAM_LOGI("start");
432     auto contextCallback = GetAuthContextCallback(apiVersion, challenge, authType, authTrustLevel, callback);
433     if (contextCallback == nullptr) {
434         IAM_LOGE("contextCallback is nullptr");
435         return BAD_CONTEXT_ID;
436     }
437     std::string callerName = "";
438     Attributes extraInfo;
439     int32_t callerType = 0;
440     if ((!IpcCommon::GetCallerName(*this, callerName, callerType))) {
441         IAM_LOGE("get bundle name fail");
442         contextCallback->OnResult(GENERAL_ERROR, extraInfo);
443         return BAD_CONTEXT_ID;
444     }
445     contextCallback->SetTraceCallerName(callerName);
446     contextCallback->SetTraceCallerType(callerType);
447     int32_t checkRet = CheckAuthPermissionAndParam(authType, callerType, callerName, authTrustLevel);
448     if (checkRet != SUCCESS) {
449         IAM_LOGE("check auth permission and param fail");
450         contextCallback->OnResult(checkRet, extraInfo);
451         return BAD_CONTEXT_ID;
452     }
453     int32_t userId = INVALID_USER_ID;
454     if (IpcCommon::GetCallingUserId(*this, userId) != SUCCESS) {
455         IAM_LOGE("get callingUserId failed");
456         contextCallback->OnResult(GENERAL_ERROR, extraInfo);
457         return BAD_CONTEXT_ID;
458     }
459     contextCallback->SetTraceUserId(userId);
460     Authentication::AuthenticationPara para = {};
461     para.tokenId = IpcCommon::GetAccessTokenId(*this);
462     para.userId = userId;
463     para.authType = authType;
464     para.atl = authTrustLevel;
465     para.challenge = std::move(challenge);
466     para.endAfterFirstFail = true;
467     para.callerName = callerName;
468     para.callerType = callerType;
469     para.sdkVersion = apiVersion;
470     para.authIntent = AuthIntent::DEFAULT;
471     para.isOsAccountVerified = GetAndUpateOsAccountVerifiedState(userId);
472     return StartAuthContext(apiVersion, para, contextCallback);
473 }
474 
StartAuthContext(int32_t apiVersion,Authentication::AuthenticationPara para,const std::shared_ptr<ContextCallback> & contextCallback)475 uint64_t UserAuthService::StartAuthContext(int32_t apiVersion, Authentication::AuthenticationPara para,
476     const std::shared_ptr<ContextCallback> &contextCallback)
477 {
478     Attributes extraInfo;
479     auto context = ContextFactory::CreateSimpleAuthContext(para, contextCallback);
480     if (context == nullptr || !ContextPool::Instance().Insert(context)) {
481         IAM_LOGE("failed to insert context");
482         contextCallback->OnResult(GENERAL_ERROR, extraInfo);
483         return BAD_CONTEXT_ID;
484     }
485     contextCallback->SetTraceRequestContextId(context->GetContextId());
486     contextCallback->SetTraceAuthContextId(context->GetContextId());
487     contextCallback->SetCleaner(ContextHelper::Cleaner(context));
488 
489     if (!context->Start()) {
490         int32_t errorCode = context->GetLatestError();
491         IAM_LOGE("failed to start auth apiVersion:%{public}d errorCode:%{public}d", apiVersion, errorCode);
492         contextCallback->OnResult(errorCode, extraInfo);
493         return BAD_CONTEXT_ID;
494     }
495     return context->GetContextId();
496 }
497 
StartRemoteAuthInvokerContext(AuthParamInner authParam,RemoteAuthInvokerContextParam & param,const std::shared_ptr<ContextCallback> & contextCallback)498 uint64_t UserAuthService::StartRemoteAuthInvokerContext(AuthParamInner authParam,
499     RemoteAuthInvokerContextParam &param, const std::shared_ptr<ContextCallback> &contextCallback)
500 {
501     Attributes extraInfo;
502     std::shared_ptr<Context> context = ContextFactory::CreateRemoteAuthInvokerContext(authParam, param,
503         contextCallback);
504     if (context == nullptr || !ContextPool::Instance().Insert(context)) {
505         IAM_LOGE("failed to insert context");
506         contextCallback->OnResult(GENERAL_ERROR, extraInfo);
507         return BAD_CONTEXT_ID;
508     }
509     contextCallback->SetCleaner(ContextHelper::Cleaner(context));
510 
511     if (!context->Start()) {
512         int32_t errorCode = context->GetLatestError();
513         IAM_LOGE("failed to start auth errorCode:%{public}d", errorCode);
514         contextCallback->OnResult(errorCode, extraInfo);
515         return BAD_CONTEXT_ID;
516     }
517     return context->GetContextId();
518 }
519 
CheckAuthPermissionAndParam(AuthType authType,AuthTrustLevel authTrustLevel,const std::shared_ptr<ContextCallback> & contextCallback,Attributes & extraInfo)520 bool UserAuthService::CheckAuthPermissionAndParam(AuthType authType, AuthTrustLevel authTrustLevel,
521     const std::shared_ptr<ContextCallback> &contextCallback, Attributes &extraInfo)
522 {
523     if (!CheckAuthTrustLevel(authTrustLevel)) {
524         IAM_LOGE("authTrustLevel is not in correct range");
525         contextCallback->OnResult(TRUST_LEVEL_NOT_SUPPORT, extraInfo);
526         return false;
527     }
528     if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
529         IAM_LOGE("failed to check permission");
530         contextCallback->OnResult(CHECK_PERMISSION_FAILED, extraInfo);
531         return false;
532     }
533     if (!SystemParamManager::GetInstance().IsAuthTypeEnable(authType)) {
534         IAM_LOGE("auth type not support");
535         contextCallback->OnResult(TYPE_NOT_SUPPORT, extraInfo);
536         return false;
537     }
538     return true;
539 }
540 
AuthUser(AuthParamInner & authParam,std::optional<RemoteAuthParam> & remoteAuthParam,sptr<UserAuthCallbackInterface> & callback)541 uint64_t UserAuthService::AuthUser(AuthParamInner &authParam, std::optional<RemoteAuthParam> &remoteAuthParam,
542     sptr<UserAuthCallbackInterface> &callback)
543 {
544     IAM_LOGI("start, %{public}s", GetAuthParamStr(authParam, remoteAuthParam).c_str());
545     Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
546     auto contextCallback = GetAuthContextCallback(INNER_API_VERSION_10000, authParam.challenge, authParam.authType,
547         authParam.authTrustLevel, callback);
548     if (contextCallback == nullptr) {
549         IAM_LOGE("contextCallback is nullptr");
550         return BAD_CONTEXT_ID;
551     }
552     contextCallback->SetTraceUserId(authParam.userId);
553     Attributes extraInfo;
554     std::string callerName = "";
555     int32_t callerType = 0;
556     if ((!IpcCommon::GetCallerName(*this, callerName, callerType))) {
557         IAM_LOGE("get caller name fail");
558         contextCallback->OnResult(GENERAL_ERROR, extraInfo);
559         return BAD_CONTEXT_ID;
560     }
561     contextCallback->SetTraceCallerName(callerName);
562     contextCallback->SetTraceCallerType(callerType);
563     if (CheckAuthPermissionAndParam(authParam.authType, authParam.authTrustLevel, contextCallback,
564         extraInfo) == false) {
565         return BAD_CONTEXT_ID;
566     }
567     Authentication::AuthenticationPara para = {};
568     para.tokenId = IpcCommon::GetAccessTokenId(*this);
569     para.userId = authParam.userId;
570     para.authType = authParam.authType;
571     para.atl = authParam.authTrustLevel;
572     para.challenge = authParam.challenge;
573     para.endAfterFirstFail = false;
574     para.callerName = callerName;
575     para.callerType = callerType;
576     para.sdkVersion = INNER_API_VERSION_10000;
577     para.authIntent = authParam.authIntent;
578     para.isOsAccountVerified = GetAndUpateOsAccountVerifiedState(authParam.userId);
579     if (!remoteAuthParam.has_value()) {
580         return StartAuthContext(INNER_API_VERSION_10000, para, contextCallback);
581     }
582 
583     ResultCode failReason = GENERAL_ERROR;
584     uint64_t contextId = AuthRemoteUser(authParam, para, remoteAuthParam.value(), contextCallback, failReason);
585     if (contextId == BAD_CONTEXT_ID) {
586         contextCallback->OnResult(failReason, extraInfo);
587         return BAD_CONTEXT_ID;
588     }
589 
590     IAM_LOGI("success");
591     return contextId;
592 }
593 
PrepareRemoteAuthInner(const std::string & networkId)594 int32_t UserAuthService::PrepareRemoteAuthInner(const std::string &networkId)
595 {
596     IAM_LOGI("start");
597     if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
598         IAM_LOGE("failed to check permission");
599         return CHECK_PERMISSION_FAILED;
600     }
601     if (networkId.empty()) {
602         IAM_LOGE("networkId is empty");
603         return INVALID_PARAMETERS;
604     }
605 
606     std::string udid;
607     bool getUdidRet = DeviceManagerUtil::GetInstance().GetUdidByNetworkId(networkId, udid);
608     IF_FALSE_LOGE_AND_RETURN_VAL(getUdidRet, GENERAL_ERROR);
609 
610     auto hdi = HdiWrapper::GetHdiInstance();
611     IF_FALSE_LOGE_AND_RETURN_VAL(hdi != nullptr, GENERAL_ERROR);
612 
613     int32_t ret = hdi->PrepareRemoteAuth(udid);
614     IF_FALSE_LOGE_AND_RETURN_VAL(ret == HDF_SUCCESS, GENERAL_ERROR);
615 
616     IAM_LOGI("success");
617     return SUCCESS;
618 }
619 
PrepareRemoteAuth(const std::string & networkId,sptr<UserAuthCallbackInterface> & callback)620 int32_t UserAuthService::PrepareRemoteAuth(const std::string &networkId, sptr<UserAuthCallbackInterface> &callback)
621 {
622     IAM_LOGI("start");
623     Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
624     if (callback == nullptr) {
625         IAM_LOGE("callback is nullptr");
626         return INVALID_PARAMETERS;
627     }
628 
629     int32_t ret = PrepareRemoteAuthInner(networkId);
630     if (ret != SUCCESS) {
631         IAM_LOGE("failed to prepare remote auth");
632     }
633 
634     Attributes attr;
635     callback->OnResult(ret, attr);
636 
637     IAM_LOGI("success");
638     return SUCCESS;
639 }
640 
AuthRemoteUser(AuthParamInner & authParam,Authentication::AuthenticationPara & para,RemoteAuthParam & remoteAuthParam,const std::shared_ptr<ContextCallback> & contextCallback,ResultCode & failReason)641 uint64_t UserAuthService::AuthRemoteUser(AuthParamInner &authParam, Authentication::AuthenticationPara &para,
642     RemoteAuthParam &remoteAuthParam, const std::shared_ptr<ContextCallback> &contextCallback, ResultCode &failReason)
643 {
644     IAM_LOGI("start");
645     failReason = GENERAL_ERROR;
646 
647     if (para.authType != PIN) {
648         IAM_LOGE("Remote auth only support pin auth");
649         failReason = INVALID_PARAMETERS;
650         return BAD_CONTEXT_ID;
651     }
652 
653     if (authParam.userId == INVALID_USER_ID) {
654         IAM_LOGE("userid must be set for remote auth");
655         failReason = INVALID_PARAMETERS;
656         return BAD_CONTEXT_ID;
657     }
658 
659     std::string localNetworkId;
660     bool getNetworkIdRet = DeviceManagerUtil::GetInstance().GetLocalDeviceNetWorkId(localNetworkId);
661     IF_FALSE_LOGE_AND_RETURN_VAL(getNetworkIdRet, BAD_CONTEXT_ID);
662 
663     bool completeRet = CompleteRemoteAuthParam(remoteAuthParam, localNetworkId);
664     if (!completeRet) {
665         IAM_LOGE("failed to complete remote auth param");
666         failReason = INVALID_PARAMETERS;
667         return BAD_CONTEXT_ID;
668     }
669 
670     if (remoteAuthParam.collectorTokenId.has_value()) {
671         para.collectorTokenId = remoteAuthParam.collectorTokenId.value();
672     } else {
673         para.collectorTokenId = para.tokenId;
674     }
675 
676     if (remoteAuthParam.collectorNetworkId.value() == localNetworkId) {
677         RemoteAuthInvokerContextParam remoteAuthInvokerContextParam;
678         remoteAuthInvokerContextParam.connectionName = "";
679         remoteAuthInvokerContextParam.verifierNetworkId = remoteAuthParam.verifierNetworkId.value();
680         remoteAuthInvokerContextParam.collectorNetworkId = remoteAuthParam.collectorNetworkId.value();
681         remoteAuthInvokerContextParam.tokenId = para.tokenId;
682         remoteAuthInvokerContextParam.collectorTokenId = para.collectorTokenId;
683         remoteAuthInvokerContextParam.callerName = para.callerName;
684         remoteAuthInvokerContextParam.callerType = para.callerType;
685         IAM_LOGI("start remote auth invoker context");
686         return StartRemoteAuthInvokerContext(authParam, remoteAuthInvokerContextParam, contextCallback);
687     }
688 
689     RemoteAuthContextParam remoteAuthContextParam;
690     remoteAuthContextParam.authType = authParam.authType;
691     remoteAuthContextParam.connectionName = "";
692     remoteAuthContextParam.collectorNetworkId = remoteAuthParam.collectorNetworkId.value();
693     remoteAuthContextParam.executorInfoMsg = {};
694     int32_t dummyLastError = 0;
695     IAM_LOGI("start remote auth context");
696     return RemoteAuthService::GetInstance().StartRemoteAuthContext(
697         para, remoteAuthContextParam, contextCallback, dummyLastError);
698 }
699 
Identify(const std::vector<uint8_t> & challenge,AuthType authType,sptr<UserAuthCallbackInterface> & callback)700 uint64_t UserAuthService::Identify(const std::vector<uint8_t> &challenge, AuthType authType,
701     sptr<UserAuthCallbackInterface> &callback)
702 {
703     IAM_LOGI("start");
704     Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
705 
706     if (callback == nullptr) {
707         IAM_LOGE("callback is nullptr");
708         return BAD_CONTEXT_ID;
709     }
710     Attributes extraInfo;
711     auto contextCallback = ContextCallback::NewInstance(callback, TRACE_IDENTIFY);
712     if (contextCallback == nullptr) {
713         IAM_LOGE("failed to construct context callback");
714         callback->OnResult(GENERAL_ERROR, extraInfo);
715         return BAD_CONTEXT_ID;
716     }
717     if ((authType == PIN) || !SystemParamManager::GetInstance().IsAuthTypeEnable(authType)) {
718         IAM_LOGE("type not support %{public}d", authType);
719         contextCallback->OnResult(TYPE_NOT_SUPPORT, extraInfo);
720         return BAD_CONTEXT_ID;
721     }
722     if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
723         IAM_LOGE("failed to check permission");
724         contextCallback->OnResult(CHECK_PERMISSION_FAILED, extraInfo);
725         return BAD_CONTEXT_ID;
726     }
727 
728     Identification::IdentificationPara para = {};
729     para.tokenId = IpcCommon::GetAccessTokenId(*this);
730     para.authType = authType;
731     para.challenge = std::move(challenge);
732     auto context = ContextFactory::CreateIdentifyContext(para, contextCallback);
733     if (!ContextPool::Instance().Insert(context)) {
734         IAM_LOGE("failed to insert context");
735         contextCallback->OnResult(GENERAL_ERROR, extraInfo);
736         return BAD_CONTEXT_ID;
737     }
738 
739     contextCallback->SetCleaner(ContextHelper::Cleaner(context));
740 
741     if (!context->Start()) {
742         IAM_LOGE("failed to start identify");
743         contextCallback->OnResult(context->GetLatestError(), extraInfo);
744         return BAD_CONTEXT_ID;
745     }
746     return context->GetContextId();
747 }
748 
CancelAuthOrIdentify(uint64_t contextId)749 int32_t UserAuthService::CancelAuthOrIdentify(uint64_t contextId)
750 {
751     IAM_LOGI("start");
752     Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
753     bool checkRet = !IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION) &&
754         !IpcCommon::CheckPermission(*this, ACCESS_BIOMETRIC_PERMISSION);
755     if (checkRet) {
756         IAM_LOGE("failed to check permission");
757         return CHECK_PERMISSION_FAILED;
758     }
759     auto context = ContextPool::Instance().Select(contextId).lock();
760     if (context == nullptr) {
761         IAM_LOGE("context not exist");
762         return GENERAL_ERROR;
763     }
764 
765     if (context->GetTokenId() != IpcCommon::GetAccessTokenId(*this)) {
766         IAM_LOGE("failed to check tokenId");
767         return INVALID_CONTEXT_ID;
768     }
769 
770     if (!context->Stop()) {
771         IAM_LOGE("failed to cancel auth or identify");
772         return context->GetLatestError();
773     }
774 
775     return SUCCESS;
776 }
777 
GetVersion(int32_t & version)778 int32_t UserAuthService::GetVersion(int32_t &version)
779 {
780     IAM_LOGI("start");
781     version = MINIMUM_VERSION;
782     bool checkRet = !IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION) &&
783         !IpcCommon::CheckPermission(*this, ACCESS_BIOMETRIC_PERMISSION);
784     if (checkRet) {
785         IAM_LOGE("failed to check permission");
786         return CHECK_PERMISSION_FAILED;
787     }
788     version = CURRENT_VERSION;
789     return SUCCESS;
790 }
791 
CheckAuthWidgetType(const std::vector<AuthType> & authType)792 int32_t UserAuthService::CheckAuthWidgetType(const std::vector<AuthType> &authType)
793 {
794     if (authType.empty() || (authType.size() > MAX_AUTH_TYPE_SIZE)) {
795         IAM_LOGE("invalid authType size:%{public}zu", authType.size());
796         return INVALID_PARAMETERS;
797     }
798     for (auto &type : authType) {
799         if ((type != AuthType::PIN) && (type != AuthType::FACE) && (type != AuthType::FINGERPRINT)) {
800             IAM_LOGE("unsupport auth type %{public}d", type);
801             return TYPE_NOT_SUPPORT;
802         }
803     }
804     std::set<AuthType> typeChecker(authType.begin(), authType.end());
805     if (typeChecker.size() != authType.size()) {
806         IAM_LOGE("duplicate auth type");
807         return INVALID_PARAMETERS;
808     }
809     return SUCCESS;
810 }
811 
CheckSingeFaceOrFinger(const std::vector<AuthType> & authType)812 bool UserAuthService::CheckSingeFaceOrFinger(const std::vector<AuthType> &authType)
813 {
814     const size_t sizeOne = 1;
815     const size_t type0 = 0;
816     if (authType.size() != sizeOne) {
817         return false;
818     }
819     if (authType[type0] == AuthType::FACE) {
820         return true;
821     }
822     if (authType[type0] == AuthType::FINGERPRINT) {
823         return true;
824     }
825     return false;
826 }
827 
CheckAuthPermissionAndParam(const AuthParamInner & authParam,const WidgetParam & widgetParam,bool isBackgroundApplication)828 int32_t UserAuthService::CheckAuthPermissionAndParam(const AuthParamInner &authParam, const WidgetParam &widgetParam,
829     bool isBackgroundApplication)
830 {
831     if (!IpcCommon::CheckPermission(*this, IS_SYSTEM_APP) &&
832         (widgetParam.windowMode != WindowModeType::UNKNOWN_WINDOW_MODE)) {
833         IAM_LOGE("normal app can't set window mode.");
834         return INVALID_PARAMETERS;
835     }
836     if (!authParam.isUserIdSpecified && !IpcCommon::CheckPermission(*this, ACCESS_BIOMETRIC_PERMISSION)) {
837         IAM_LOGE("CheckPermission failed");
838         return CHECK_PERMISSION_FAILED;
839     }
840     if (authParam.isUserIdSpecified && !IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
841         IAM_LOGE("CheckPermission failed");
842         return CHECK_PERMISSION_FAILED;
843     }
844     int32_t ret = CheckAuthWidgetType(authParam.authTypes);
845     if (ret != SUCCESS) {
846         IAM_LOGE("CheckAuthWidgetType fail.");
847         return ret;
848     }
849     if (!CheckAuthTrustLevel(authParam.authTrustLevel)) {
850         IAM_LOGE("authTrustLevel is not in correct range");
851         return ResultCode::TRUST_LEVEL_NOT_SUPPORT;
852     }
853     static const size_t authTypeTwo = 2;
854     static const size_t authType0 = 0;
855     static const size_t authType1 = 1;
856     std::vector<AuthType> authType = authParam.authTypes;
857     if (((authType.size() == authTypeTwo) &&
858             (authType[authType0] == AuthType::FACE) && (authType[authType1] == AuthType::FINGERPRINT)) ||
859         ((authType.size() == authTypeTwo) &&
860             (authType[authType0] == AuthType::FINGERPRINT) && (authType[authType1] == AuthType::FACE))) {
861         IAM_LOGE("only face and finger not support");
862         return INVALID_PARAMETERS;
863     }
864     if (widgetParam.title.empty()) {
865         IAM_LOGE("title is empty");
866         return INVALID_PARAMETERS;
867     }
868     return SUCCESS;
869 }
870 
StartWidgetContext(const std::shared_ptr<ContextCallback> & contextCallback,const AuthParamInner & authParam,const WidgetParam & widgetParam,std::vector<AuthType> & validType,ContextFactory::AuthWidgetContextPara & para)871 uint64_t UserAuthService::StartWidgetContext(const std::shared_ptr<ContextCallback> &contextCallback,
872     const AuthParamInner &authParam, const WidgetParam &widgetParam, std::vector<AuthType> &validType,
873     ContextFactory::AuthWidgetContextPara &para)
874 {
875     Attributes extraInfo;
876     para.tokenId = IpcCommon::GetAccessTokenId(*this);
877     para.isOsAccountVerified = IpcCommon::IsOsAccountVerified(para.userId);
878     if (!AuthWidgetHelper::InitWidgetContextParam(authParam, validType, widgetParam, para)) {
879         IAM_LOGE("init widgetContext failed");
880         contextCallback->OnResult(ResultCode::GENERAL_ERROR, extraInfo);
881         return BAD_CONTEXT_ID;
882     }
883     auto context = ContextFactory::CreateWidgetContext(para, contextCallback);
884     if (context == nullptr || !Insert2ContextPool(context)) {
885         contextCallback->OnResult(ResultCode::GENERAL_ERROR, extraInfo);
886         return BAD_CONTEXT_ID;
887     }
888     contextCallback->SetTraceRequestContextId(context->GetContextId());
889     contextCallback->SetCleaner(ContextHelper::Cleaner(context));
890     if (!context->Start()) {
891         int32_t errorCode = context->GetLatestError();
892         IAM_LOGE("start widget context fail %{public}d", errorCode);
893         contextCallback->OnResult(errorCode, extraInfo);
894         return BAD_CONTEXT_ID;
895     }
896     return context->GetContextId();
897 }
898 
CheckValidSolution(int32_t userId,const AuthParamInner & authParam,const WidgetParam & widgetParam,std::vector<AuthType> & validType)899 int32_t UserAuthService::CheckValidSolution(int32_t userId, const AuthParamInner &authParam,
900     const WidgetParam &widgetParam, std::vector<AuthType> &validType)
901 {
902     int32_t ret = AuthWidgetHelper::CheckValidSolution(
903         userId, authParam.authTypes, authParam.authTrustLevel, validType);
904     if (ret != SUCCESS) {
905         IAM_LOGE("CheckValidSolution fail %{public}d", ret);
906         return ret;
907     }
908     if (!widgetParam.navigationButtonText.empty() && !CheckSingeFaceOrFinger(validType)) {
909         IAM_LOGE("navigationButtonText check fail, validType.size:%{public}zu", validType.size());
910         return INVALID_PARAMETERS;
911     }
912     if (widgetParam.windowMode == FULLSCREEN && CheckSingeFaceOrFinger(validType)) {
913         IAM_LOGE("Single fingerprint or single face does not support full screen");
914         return INVALID_PARAMETERS;
915     }
916     return SUCCESS;
917 }
918 
GetCallerInfo(bool isUserIdSpecified,int32_t userId,ContextFactory::AuthWidgetContextPara & para,bool & isBackgroundApplication,std::shared_ptr<ContextCallback> & contextCallback)919 int32_t UserAuthService::GetCallerInfo(bool isUserIdSpecified, int32_t userId,
920     ContextFactory::AuthWidgetContextPara &para, bool &isBackgroundApplication,
921     std::shared_ptr<ContextCallback> &contextCallback)
922 {
923     static_cast<void>(IpcCommon::GetCallerName(*this, para.callerName, para.callerType));
924     contextCallback->SetTraceCallerName(para.callerName);
925     contextCallback->SetTraceCallerType(para.callerType);
926     static_cast<void>(IpcCommon::GetCallingAppID(*this, para.callingAppID));
927 
928     if (para.sdkVersion < INNER_API_VERSION_10000 && para.callerType == Security::AccessToken::TOKEN_HAP &&
929         (!IpcCommon::CheckForegroundApplication(para.callerName))) {
930         isBackgroundApplication = true;
931     }
932     contextCallback->SetTraceIsBackgroundApplication(isBackgroundApplication);
933 
934     if (isUserIdSpecified) {
935         para.userId = userId;
936         contextCallback->SetTraceUserId(para.userId);
937         return SUCCESS;
938     }
939     if (IpcCommon::GetCallingUserId(*this, para.userId) != SUCCESS) {
940         IAM_LOGE("get callingUserId failed");
941         return GENERAL_ERROR;
942     }
943     contextCallback->SetTraceUserId(para.userId);
944     return SUCCESS;
945 }
946 
AuthWidget(int32_t apiVersion,const AuthParamInner & authParam,const WidgetParam & widgetParam,sptr<UserAuthCallbackInterface> & callback)947 uint64_t UserAuthService::AuthWidget(int32_t apiVersion, const AuthParamInner &authParam,
948     const WidgetParam &widgetParam, sptr<UserAuthCallbackInterface> &callback)
949 {
950     IAM_LOGI("start %{public}d authTrustLevel:%{public}u", apiVersion, authParam.authTrustLevel);
951     auto contextCallback = GetAuthContextCallback(apiVersion, authParam, widgetParam, callback);
952     if (contextCallback == nullptr) {
953         IAM_LOGE("contextCallback is nullptr");
954         return BAD_CONTEXT_ID;
955     }
956     ContextFactory::AuthWidgetContextPara para;
957     para.sdkVersion = apiVersion;
958     Attributes extraInfo;
959     bool isBackgroundApplication = false;
960     int32_t checkRet = GetCallerInfo(authParam.isUserIdSpecified, authParam.userId, para, isBackgroundApplication,
961         contextCallback);
962     if (checkRet != SUCCESS) {
963         contextCallback->OnResult(checkRet, extraInfo);
964         return BAD_CONTEXT_ID;
965     }
966     checkRet = CheckAuthPermissionAndParam(authParam, widgetParam, isBackgroundApplication);
967     if (checkRet != SUCCESS) {
968         IAM_LOGE("check permission and auth widget param failed");
969         contextCallback->OnResult(checkRet, extraInfo);
970         return BAD_CONTEXT_ID;
971     }
972 
973     if (AuthWidgetHelper::CheckReuseUnlockResult(para, authParam, extraInfo) == SUCCESS) {
974         IAM_LOGE("check reuse unlock result success");
975         contextCallback->OnResult(SUCCESS, extraInfo);
976         return REUSE_AUTH_RESULT_CONTEXT_ID;
977     }
978     std::vector<AuthType> validType;
979     checkRet = CheckValidSolution(para.userId, authParam, widgetParam, validType);
980     if (checkRet != SUCCESS && checkRet != PIN_EXPIRED) {
981         IAM_LOGE("check valid solution failed");
982         contextCallback->OnResult(checkRet, extraInfo);
983         return BAD_CONTEXT_ID;
984     }
985     if (checkRet == PIN_EXPIRED) {
986         para.isPinExpired = true;
987         validType.emplace_back(AuthType::PIN);
988     }
989     return StartWidgetContext(contextCallback, authParam, widgetParam, validType, para);
990 }
991 
Insert2ContextPool(const std::shared_ptr<Context> & context)992 bool UserAuthService::Insert2ContextPool(const std::shared_ptr<Context> &context)
993 {
994     bool ret = false;
995     const int32_t retryTimes = 3;
996     for (auto i = 0; i < retryTimes; i++) {
997         ret = ContextPool::Instance().Insert(context);
998         if (ret) {
999             break;
1000         }
1001     }
1002     IAM_LOGI("insert context to pool, retry %{public}d times", retryTimes);
1003     return ret;
1004 }
1005 
GetAuthContextCallback(int32_t apiVersion,const AuthParamInner & authParam,const WidgetParam & widgetParam,sptr<UserAuthCallbackInterface> & callback)1006 std::shared_ptr<ContextCallback> UserAuthService::GetAuthContextCallback(int32_t apiVersion,
1007     const AuthParamInner &authParam, const WidgetParam &widgetParam, sptr<UserAuthCallbackInterface> &callback)
1008 {
1009     if (callback == nullptr) {
1010         IAM_LOGE("callback is nullptr");
1011         return nullptr;
1012     }
1013     auto contextCallback = ContextCallback::NewInstance(callback, TRACE_AUTH_USER_BEHAVIOR);
1014     if (contextCallback == nullptr) {
1015         IAM_LOGE("failed to construct context callback");
1016         Attributes extraInfo;
1017         callback->OnResult(ResultCode::GENERAL_ERROR, extraInfo);
1018         return nullptr;
1019     }
1020     contextCallback->SetTraceSdkVersion(apiVersion);
1021     contextCallback->SetTraceAuthTrustLevel(authParam.authTrustLevel);
1022 
1023     uint32_t authWidgetType = 0;
1024     for (const auto authType : authParam.authTypes) {
1025         authWidgetType |= static_cast<uint32_t>(authType);
1026     }
1027     static const uint32_t bitWindowMode = 0x40000000;
1028     if (widgetParam.windowMode == FULLSCREEN) {
1029         authWidgetType |= bitWindowMode;
1030     }
1031     static const uint32_t bitNavigation = 0x80000000;
1032     if (!widgetParam.navigationButtonText.empty()) {
1033         authWidgetType |= bitNavigation;
1034     }
1035     IAM_LOGI("SetTraceAuthWidgetType %{public}08x", authWidgetType);
1036     contextCallback->SetTraceAuthWidgetType(authWidgetType);
1037     uint32_t traceReuseMode = 0;
1038     uint64_t traceReuseDuration = 0;
1039     if (authParam.reuseUnlockResult.isReuse) {
1040         traceReuseMode = authParam.reuseUnlockResult.reuseMode;
1041         traceReuseDuration = authParam.reuseUnlockResult.reuseDuration;
1042     }
1043     contextCallback->SetTraceReuseUnlockResultMode(traceReuseMode);
1044     contextCallback->SetTraceReuseUnlockResultDuration(traceReuseDuration);
1045     return contextCallback;
1046 }
1047 
Notice(NoticeType noticeType,const std::string & eventData)1048 int32_t UserAuthService::Notice(NoticeType noticeType, const std::string &eventData)
1049 {
1050     IAM_LOGI("start");
1051     if (!IpcCommon::CheckPermission(*this, IS_SYSTEM_APP)) {
1052         IAM_LOGE("the caller is not a system application");
1053         return ResultCode::CHECK_SYSTEM_APP_FAILED;
1054     }
1055 
1056     if (!IpcCommon::CheckPermission(*this, SUPPORT_USER_AUTH)) {
1057         IAM_LOGE("failed to check permission");
1058         return ResultCode::CHECK_PERMISSION_FAILED;
1059     }
1060     return WidgetClient::Instance().OnNotice(noticeType, eventData);
1061 }
1062 
RegisterWidgetCallback(int32_t version,sptr<WidgetCallbackInterface> & callback)1063 int32_t UserAuthService::RegisterWidgetCallback(int32_t version, sptr<WidgetCallbackInterface> &callback)
1064 {
1065     if (!IpcCommon::CheckPermission(*this, IS_SYSTEM_APP)) {
1066         IAM_LOGE("the caller is not a system application");
1067         return ResultCode::CHECK_SYSTEM_APP_FAILED;
1068     }
1069 
1070     if (!IpcCommon::CheckPermission(*this, SUPPORT_USER_AUTH)) {
1071         IAM_LOGE("CheckPermission failed, no permission");
1072         return ResultCode::CHECK_PERMISSION_FAILED;
1073     }
1074 
1075     uint32_t tokenId = IpcCommon::GetTokenId(*this);
1076     IAM_LOGE("RegisterWidgetCallback tokenId %{public}s", GET_MASKED_STRING(tokenId).c_str());
1077 
1078     int32_t curVersion = std::stoi(NOTICE_VERSION_STR);
1079     if (version != curVersion) {
1080         return ResultCode::INVALID_PARAMETERS;
1081     }
1082     if (callback == nullptr) {
1083         IAM_LOGE("callback is nullptr");
1084         return ResultCode::INVALID_PARAMETERS;
1085     }
1086     WidgetClient::Instance().SetWidgetCallback(callback);
1087     WidgetClient::Instance().SetAuthTokenId(tokenId);
1088     return ResultCode::SUCCESS;
1089 }
1090 
GetEnrolledState(int32_t apiVersion,AuthType authType,EnrolledState & enrolledState)1091 int32_t UserAuthService::GetEnrolledState(int32_t apiVersion, AuthType authType,
1092     EnrolledState &enrolledState)
1093 {
1094     IAM_LOGI("start");
1095 
1096     if (!IpcCommon::CheckPermission(*this, ACCESS_BIOMETRIC_PERMISSION)) {
1097         IAM_LOGE("failed to check permission");
1098         return CHECK_PERMISSION_FAILED;
1099     }
1100 
1101     if (apiVersion < API_VERSION_12 ||
1102         !SystemParamManager::GetInstance().IsAuthTypeEnable(authType)) {
1103         IAM_LOGE("failed to check apiVersion");
1104         return TYPE_NOT_SUPPORT;
1105     }
1106 
1107     int32_t userId = INVALID_USER_ID;
1108     if (IpcCommon::GetCallingUserId(*this, userId) != SUCCESS) {
1109         IAM_LOGE("failed to get callingUserId");
1110         return GENERAL_ERROR;
1111     }
1112 
1113     auto hdi = HdiWrapper::GetHdiInstance();
1114     if (hdi == nullptr) {
1115         IAM_LOGE("hdi interface is nullptr");
1116         return GENERAL_ERROR;
1117     }
1118     HdiEnrolledState hdiEnrolledState = {};
1119     int32_t result = hdi->GetEnrolledState(userId, static_cast<HdiAuthType>(authType), hdiEnrolledState);
1120     if (result != SUCCESS) {
1121         IAM_LOGE("failed to get enrolled state,userId:%{public}d authType:%{public}d", userId, authType);
1122         return result;
1123     }
1124     enrolledState.credentialCount = hdiEnrolledState.credentialCount;
1125     enrolledState.credentialDigest = hdiEnrolledState.credentialDigest;
1126     if (apiVersion < INNER_API_VERSION_10000) {
1127         enrolledState.credentialDigest = hdiEnrolledState.credentialDigest & UINT16_MAX;
1128     }
1129     return SUCCESS;
1130 }
1131 
CheckAuthTypeIsValid(std::vector<AuthType> authType)1132 bool UserAuthService::CheckAuthTypeIsValid(std::vector<AuthType> authType)
1133 {
1134     if (authType.empty()) {
1135         return false;
1136     }
1137     for (const auto &iter : authType) {
1138         if (iter != AuthType::PIN && iter != AuthType::FACE && iter != AuthType::FINGERPRINT) {
1139             return false;
1140         }
1141     }
1142     return true;
1143 }
1144 
RegistUserAuthSuccessEventListener(const std::vector<AuthType> & authType,const sptr<AuthEventListenerInterface> & listener)1145 int32_t UserAuthService::RegistUserAuthSuccessEventListener(const std::vector<AuthType> &authType,
1146     const sptr<AuthEventListenerInterface> &listener)
1147 {
1148     IAM_LOGI("start");
1149     Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
1150     IF_FALSE_LOGE_AND_RETURN_VAL(listener != nullptr, INVALID_PARAMETERS);
1151 
1152     if (!CheckAuthTypeIsValid(authType)) {
1153         IAM_LOGE("failed to check authType");
1154         return INVALID_PARAMETERS;
1155     }
1156 
1157     if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
1158         IAM_LOGE("failed to check permission");
1159         return CHECK_PERMISSION_FAILED;
1160     }
1161 
1162     int32_t result = AuthEventListenerManager::GetInstance().RegistUserAuthSuccessEventListener(authType, listener);
1163     if (result != SUCCESS) {
1164         IAM_LOGE("failed to regist auth event listener");
1165         return result;
1166     }
1167 
1168     return SUCCESS;
1169 }
1170 
UnRegistUserAuthSuccessEventListener(const sptr<AuthEventListenerInterface> & listener)1171 int32_t UserAuthService::UnRegistUserAuthSuccessEventListener(
1172     const sptr<AuthEventListenerInterface> &listener)
1173 {
1174     IAM_LOGI("start");
1175     Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
1176     IF_FALSE_LOGE_AND_RETURN_VAL(listener != nullptr, INVALID_PARAMETERS);
1177 
1178     if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
1179         IAM_LOGE("failed to check permission");
1180         return CHECK_PERMISSION_FAILED;
1181     }
1182 
1183     int32_t result = AuthEventListenerManager::GetInstance().UnRegistUserAuthSuccessEventListener(listener);
1184     if (result != SUCCESS) {
1185         IAM_LOGE("failed to unregist auth event listener");
1186         return result;
1187     }
1188 
1189     return SUCCESS;
1190 }
1191 
SetGlobalConfigParam(const GlobalConfigParam & param)1192 int32_t UserAuthService::SetGlobalConfigParam(const GlobalConfigParam &param)
1193 {
1194     IAM_LOGI("start");
1195     Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
1196     if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
1197         IAM_LOGE("failed to check permission");
1198         return CHECK_PERMISSION_FAILED;
1199     }
1200     if (param.type != PIN_EXPIRED_PERIOD) {
1201         IAM_LOGE("bad global config type");
1202         return INVALID_PARAMETERS;
1203     }
1204     HdiGlobalConfigParam paramConfig = {};
1205     paramConfig.type = PIN_EXPIRED_PERIOD;
1206     paramConfig.value.pinExpiredPeriod = param.value.pinExpiredPeriod;
1207 
1208     auto hdi = HdiWrapper::GetHdiInstance();
1209     if (hdi == nullptr) {
1210         IAM_LOGE("hdi interface is nullptr");
1211         return GENERAL_ERROR;
1212     }
1213     int32_t result = hdi->SetGlobalConfigParam(paramConfig);
1214     if (result != SUCCESS) {
1215         IAM_LOGE("failed to Set global config param");
1216         return result;
1217     }
1218 
1219     return SUCCESS;
1220 }
1221 
CompleteRemoteAuthParam(RemoteAuthParam & remoteAuthParam,const std::string & localNetworkId)1222 bool UserAuthService::CompleteRemoteAuthParam(RemoteAuthParam &remoteAuthParam, const std::string &localNetworkId)
1223 {
1224     IAM_LOGI("start");
1225     if (remoteAuthParam.verifierNetworkId.has_value() && remoteAuthParam.verifierNetworkId->size() !=
1226         NETWORK_ID_LENGTH) {
1227         IAM_LOGE("invalid verifierNetworkId size");
1228         return false;
1229     }
1230 
1231     if (remoteAuthParam.collectorNetworkId.has_value() && remoteAuthParam.collectorNetworkId->size() !=
1232         NETWORK_ID_LENGTH) {
1233         IAM_LOGE("invalid collectorNetworkId size");
1234         return false;
1235     }
1236 
1237     if (!remoteAuthParam.verifierNetworkId.has_value() && !remoteAuthParam.collectorNetworkId.has_value()) {
1238         IAM_LOGE("neither verifierNetworkId nor collectorNetworkId is set");
1239         return false;
1240     } else if (remoteAuthParam.verifierNetworkId.has_value() && !remoteAuthParam.collectorNetworkId.has_value()) {
1241         IAM_LOGI("collectorNetworkId not set, verifierNetworkId set, use local networkId as collectorNetworkId");
1242         remoteAuthParam.collectorNetworkId = localNetworkId;
1243     } else if (!remoteAuthParam.verifierNetworkId.has_value() && remoteAuthParam.collectorNetworkId.has_value()) {
1244         IAM_LOGI("verifierNetworkId not set, collectorNetworkId set, use local networkId as verifierNetworkId");
1245         remoteAuthParam.verifierNetworkId = localNetworkId;
1246     }
1247 
1248     if (remoteAuthParam.verifierNetworkId.value() != localNetworkId &&
1249         remoteAuthParam.collectorNetworkId.value() != localNetworkId) {
1250         IAM_LOGE("both verifierNetworkId and collectorNetworkId are not local networkId");
1251         return false;
1252     }
1253 
1254     if (remoteAuthParam.verifierNetworkId.value() == remoteAuthParam.collectorNetworkId.value()) {
1255         IAM_LOGE("verifierNetworkId and collectorNetworkId are the same");
1256         return false;
1257     }
1258 
1259     if (remoteAuthParam.verifierNetworkId == localNetworkId && !remoteAuthParam.collectorTokenId.has_value()) {
1260         IAM_LOGE("this device is verifier, collectorTokenId not set");
1261         return false;
1262     }
1263 
1264     if (remoteAuthParam.collectorNetworkId == localNetworkId && !remoteAuthParam.collectorTokenId.has_value()) {
1265         IAM_LOGI("this device is collector, update collectorTokenId with caller token id");
1266         remoteAuthParam.collectorTokenId = IpcCommon::GetAccessTokenId(*this);
1267     }
1268 
1269     IAM_LOGI("success");
1270     return true;
1271 }
1272 
GetAndUpateOsAccountVerifiedState(int32_t userId)1273 bool UserAuthService::GetAndUpateOsAccountVerifiedState(int32_t userId)
1274 {
1275     IAM_LOGI("start");
1276     if (osAccountVerifiedState_ == false) {
1277         osAccountVerifiedState_ = IpcCommon::IsOsAccountVerified(userId);
1278     }
1279 
1280     return osAccountVerifiedState_;
1281 }
1282 } // namespace UserAuth
1283 } // namespace UserIam
1284 } // namespace OHOS