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