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 "context_helper.h"
27 #include "hdi_wrapper.h"
28 #include "iam_check.h"
29 #include "iam_common_defines.h"
30 #include "iam_logger.h"
31 #include "iam_para2str.h"
32 #include "iam_ptr.h"
33 #include "iam_time.h"
34 #include "ipc_common.h"
35 #include "ipc_skeleton.h"
36 #include "keyguard_status_listener.h"
37 #include "service_init_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 #include "xcollie_helper.h"
45
46 #define LOG_TAG "USER_AUTH_SA"
47
48 namespace OHOS {
49 namespace UserIam {
50 namespace UserAuth {
51 namespace {
52 const int32_t MINIMUM_VERSION = 0;
53 const int32_t CURRENT_VERSION = 1;
54 const int32_t USERIAM_IPC_THREAD_NUM = 4;
55 const uint32_t NETWORK_ID_LENGTH = 64;
GetTemplatesByAuthType(int32_t userId,AuthType authType,std::vector<uint64_t> & templateIds)56 int32_t GetTemplatesByAuthType(int32_t userId, AuthType authType, std::vector<uint64_t> &templateIds)
57 {
58 templateIds.clear();
59 std::vector<std::shared_ptr<CredentialInfoInterface>> credentialInfos;
60 int32_t ret = UserIdmDatabase::Instance().GetCredentialInfo(userId, authType, credentialInfos);
61 if (ret != SUCCESS) {
62 IAM_LOGE("get credential fail, ret:%{public}d, userId:%{public}d, authType:%{public}d", ret,
63 userId, authType);
64 return GENERAL_ERROR;
65 }
66
67 if (credentialInfos.empty()) {
68 IAM_LOGE("user %{public}d has no credential type %{public}d", userId, authType);
69 return SUCCESS;
70 }
71
72 templateIds.reserve(credentialInfos.size());
73 for (auto &info : credentialInfos) {
74 if (info == nullptr) {
75 IAM_LOGE("info is nullptr");
76 continue;
77 }
78 templateIds.push_back(info->GetTemplateId());
79 }
80
81 return SUCCESS;
82 }
83
IsTemplateIdListRequired(const std::vector<Attributes::AttributeKey> & keys)84 bool IsTemplateIdListRequired(const std::vector<Attributes::AttributeKey> &keys)
85 {
86 for (const auto &key : keys) {
87 if (key == Attributes::AttributeKey::ATTR_PIN_SUB_TYPE ||
88 key == Attributes::AttributeKey::ATTR_REMAIN_TIMES ||
89 key == Attributes::AttributeKey::ATTR_FREEZING_TIME ||
90 key == Attributes::AttributeKey::ATTR_NEXT_FAIL_LOCKOUT_DURATION) {
91 return true;
92 }
93 }
94 return false;
95 }
96
GetResourceNodeByTypeAndRole(AuthType authType,ExecutorRole role,std::vector<std::weak_ptr<ResourceNode>> & authTypeNodes)97 void GetResourceNodeByTypeAndRole(AuthType authType, ExecutorRole role,
98 std::vector<std::weak_ptr<ResourceNode>> &authTypeNodes)
99 {
100 authTypeNodes.clear();
101 ResourceNodePool::Instance().Enumerate(
102 [&authTypeNodes, role, authType](const std::weak_ptr<ResourceNode> &weakNode) {
103 auto node = weakNode.lock();
104 if (node == nullptr) {
105 return;
106 }
107 if (node->GetAuthType() != authType) {
108 return;
109 }
110 if (node->GetExecutorRole() != role) {
111 return;
112 }
113 authTypeNodes.push_back(node);
114 });
115 }
116
GetAuthParamStr(const AuthParamInner & authParam,std::optional<RemoteAuthParam> & remoteAuthParam)117 std::string GetAuthParamStr(const AuthParamInner &authParam, std::optional<RemoteAuthParam> &remoteAuthParam)
118 {
119 std::ostringstream authParamString;
120 authParamString << "userId:" << authParam.userId << " authType:" << authParam.authType
121 << " authIntent:" << authParam.authIntent << " atl:" << authParam.authTrustLevel;
122 if (remoteAuthParam.has_value()) {
123 const uint32_t networkIdPrintLen = 4;
124 const uint32_t tokenIdMinLen = 2;
125 auto verifierNetworkIdStr = remoteAuthParam->verifierNetworkId.value_or("").substr(0, networkIdPrintLen);
126 auto collectorNetworkIdStr = remoteAuthParam->collectorNetworkId.value_or("").substr(0, networkIdPrintLen);
127 auto tokenIdStr = std::to_string(remoteAuthParam->collectorTokenId.value_or(0));
128 if (tokenIdStr.size() > tokenIdMinLen) {
129 tokenIdStr = std::string(1, tokenIdStr[0]) + "****" + std::string(1, tokenIdStr[tokenIdStr.size() - 1]);
130 } else {
131 tokenIdStr = "";
132 }
133
134 authParamString << " isRemoteAuth:true" << " verifierNetworkId:" << verifierNetworkIdStr << "****"
135 " collectorNetworkId:" << collectorNetworkIdStr << "****" << " collectorTokenId:" << tokenIdStr;
136 }
137 return authParamString.str();
138 }
139 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(UserAuthService::GetInstance().get());
140 } // namespace
141 std::mutex UserAuthService::mutex_;
142 std::shared_ptr<UserAuthService> UserAuthService::instance_ = nullptr;
143
GetInstance()144 std::shared_ptr<UserAuthService> UserAuthService::GetInstance()
145 {
146 if (instance_ == nullptr) {
147 std::lock_guard<std::mutex> guard(mutex_);
148 if (instance_ == nullptr) {
149 instance_ = Common::MakeShared<UserAuthService>();
150 if (instance_ == nullptr) {
151 IAM_LOGE("make share failed");
152 }
153 }
154 }
155 return instance_;
156 }
157
UserAuthService()158 UserAuthService::UserAuthService()
159 : SystemAbility(SUBSYS_USERIAM_SYS_ABILITY_USERAUTH, true)
160 {}
161
OnStart()162 void UserAuthService::OnStart()
163 {
164 IAM_LOGI("Sa start UserAuthService");
165 IPCSkeleton::SetMaxWorkThreadNum(USERIAM_IPC_THREAD_NUM);
166 if (!Publish(this)) {
167 IAM_LOGE("failed to publish service");
168 }
169 ServiceInitManager::GetInstance().OnUserAuthServiceStart();
170 }
171
OnStop()172 void UserAuthService::OnStop()
173 {
174 IAM_LOGI("Sa stop UserAuthService");
175 ServiceInitManager::GetInstance().OnUserAuthServiceStop();
176 }
177
CheckAuthTrustLevel(AuthTrustLevel authTrustLevel)178 bool UserAuthService::CheckAuthTrustLevel(AuthTrustLevel authTrustLevel)
179 {
180 if ((authTrustLevel != ATL1) && (authTrustLevel != ATL2) &&
181 (authTrustLevel != ATL3) && (authTrustLevel != ATL4)) {
182 IAM_LOGE("authTrustLevel not support %{public}u", authTrustLevel);
183 return false;
184 }
185 return true;
186 }
187
GetAvailableStatus(int32_t apiVersion,int32_t userId,AuthType authType,AuthTrustLevel authTrustLevel)188 int32_t UserAuthService::GetAvailableStatus(int32_t apiVersion, int32_t userId, AuthType authType,
189 AuthTrustLevel authTrustLevel)
190 {
191 IAM_LOGI("start with userId");
192
193 if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
194 IAM_LOGE("failed to check permission");
195 return CHECK_PERMISSION_FAILED;
196 }
197 return GetAvailableStatusInner(apiVersion, userId, authType, authTrustLevel);
198 }
199
GetAvailableStatus(int32_t apiVersion,AuthType authType,AuthTrustLevel authTrustLevel)200 int32_t UserAuthService::GetAvailableStatus(int32_t apiVersion, AuthType authType, AuthTrustLevel authTrustLevel)
201 {
202 IAM_LOGI("start without userId");
203
204 if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION) &&
205 !IpcCommon::CheckPermission(*this, ACCESS_BIOMETRIC_PERMISSION)) {
206 IAM_LOGE("failed to check permission");
207 return CHECK_PERMISSION_FAILED;
208 }
209 if (apiVersion <= API_VERSION_8 && authType == PIN) {
210 IAM_LOGE("authType not support");
211 return TYPE_NOT_SUPPORT;
212 }
213 int32_t userId = INVALID_USER_ID;
214 if (IpcCommon::GetCallingUserId(*this, userId) != SUCCESS) {
215 IAM_LOGE("failed to get userId");
216 return GENERAL_ERROR;
217 }
218 return GetAvailableStatusInner(apiVersion, userId, authType, authTrustLevel);
219 }
220
GetAvailableStatusInner(int32_t apiVersion,int32_t userId,AuthType authType,AuthTrustLevel authTrustLevel)221 int32_t UserAuthService::GetAvailableStatusInner(int32_t apiVersion, int32_t userId, AuthType authType,
222 AuthTrustLevel authTrustLevel)
223 {
224 if (!CheckAuthTrustLevel(authTrustLevel)) {
225 IAM_LOGE("authTrustLevel is not in correct range");
226 return TRUST_LEVEL_NOT_SUPPORT;
227 }
228 auto hdi = HdiWrapper::GetHdiInstance();
229 if (hdi == nullptr) {
230 IAM_LOGE("hdi interface is nullptr");
231 return GENERAL_ERROR;
232 }
233 int32_t checkRet = GENERAL_ERROR;
234 int32_t result = hdi->GetAvailableStatus(userId, authType, authTrustLevel, checkRet);
235 if (result != SUCCESS) {
236 IAM_LOGE("hdi GetAvailableStatus failed");
237 return GENERAL_ERROR;
238 }
239 IAM_LOGI("GetAvailableStatus result:%{public}d", checkRet);
240 return checkRet;
241 }
242
FillGetPropertyKeys(AuthType authType,const std::vector<Attributes::AttributeKey> & keys,std::vector<uint32_t> & uint32Keys)243 void UserAuthService::FillGetPropertyKeys(AuthType authType, const std::vector<Attributes::AttributeKey> &keys,
244 std::vector<uint32_t> &uint32Keys)
245 {
246 uint32Keys.reserve(keys.size());
247 for (const auto &key : keys) {
248 if (key == Attributes::ATTR_NEXT_FAIL_LOCKOUT_DURATION && authType != PIN) {
249 continue;
250 }
251 uint32Keys.push_back(static_cast<uint32_t>(key));
252 }
253 }
254
FillGetPropertyValue(AuthType authType,const std::vector<Attributes::AttributeKey> & keys,Attributes & values)255 void UserAuthService::FillGetPropertyValue(AuthType authType, const std::vector<Attributes::AttributeKey> &keys,
256 Attributes &values)
257 {
258 for (const auto &key : keys) {
259 if (key == Attributes::ATTR_NEXT_FAIL_LOCKOUT_DURATION && authType != PIN) {
260 if (!values.SetInt32Value(Attributes::ATTR_NEXT_FAIL_LOCKOUT_DURATION, FIRST_LOCKOUT_DURATION_EXCEPT_PIN)) {
261 IAM_LOGE("set nextFailLockoutDuration failed, authType %{public}d", authType);
262 }
263 break;
264 }
265 }
266 }
267
GetResourseNode(AuthType authType)268 std::shared_ptr<ResourceNode> UserAuthService::GetResourseNode(AuthType authType)
269 {
270 std::vector<std::weak_ptr<ResourceNode>> authTypeNodes;
271 GetResourceNodeByTypeAndRole(authType, ALL_IN_ONE, authTypeNodes);
272 if (authTypeNodes.size() != 1) {
273 IAM_LOGE("auth type %{public}d resource node num %{public}zu is not expected",
274 authType, authTypeNodes.size());
275 return nullptr;
276 }
277
278 auto resourceNode = authTypeNodes[0].lock();
279 if (resourceNode == nullptr) {
280 IAM_LOGE("resourceNode is nullptr");
281 return nullptr;
282 }
283
284 return resourceNode;
285 }
286
GetPropertyInner(AuthType authType,const std::vector<Attributes::AttributeKey> & keys,sptr<GetExecutorPropertyCallbackInterface> & callback,std::vector<uint64_t> & templateIds)287 void UserAuthService::GetPropertyInner(AuthType authType, const std::vector<Attributes::AttributeKey> &keys,
288 sptr<GetExecutorPropertyCallbackInterface> &callback, std::vector<uint64_t> &templateIds)
289 {
290 Attributes values;
291 auto resourceNode = GetResourseNode(authType);
292 if (resourceNode == nullptr) {
293 IAM_LOGE("resourceNode is nullptr");
294 callback->OnGetExecutorPropertyResult(GENERAL_ERROR, values);
295 return;
296 }
297
298 std::vector<uint32_t> uint32Keys;
299 FillGetPropertyKeys(authType, keys, uint32Keys);
300 Attributes attr;
301 attr.SetUint32Value(Attributes::ATTR_PROPERTY_MODE, PROPERTY_MODE_GET);
302 attr.SetUint64ArrayValue(Attributes::ATTR_TEMPLATE_ID_LIST, templateIds);
303 attr.SetUint32ArrayValue(Attributes::ATTR_KEY_LIST, uint32Keys);
304
305 int32_t result = resourceNode->GetProperty(attr, values);
306 if (result != SUCCESS) {
307 IAM_LOGE("failed to get property, result = %{public}d", result);
308 }
309 FillGetPropertyValue(authType, keys, values);
310
311 callback->OnGetExecutorPropertyResult(result, values);
312 }
313
GetProperty(int32_t userId,AuthType authType,const std::vector<Attributes::AttributeKey> & keys,sptr<GetExecutorPropertyCallbackInterface> & callback)314 void UserAuthService::GetProperty(int32_t userId, AuthType authType,
315 const std::vector<Attributes::AttributeKey> &keys, sptr<GetExecutorPropertyCallbackInterface> &callback)
316 {
317 IAM_LOGI("start");
318 Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
319 IF_FALSE_LOGE_AND_RETURN(callback != nullptr);
320 Attributes values;
321
322 if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
323 IAM_LOGE("failed to check permission");
324 callback->OnGetExecutorPropertyResult(CHECK_PERMISSION_FAILED, values);
325 return;
326 }
327
328 std::vector<uint64_t> templateIds;
329 if (IsTemplateIdListRequired(keys)) {
330 int32_t ret = GetTemplatesByAuthType(userId, authType, templateIds);
331 if (ret != SUCCESS) {
332 IAM_LOGE("get templates fail, ret:%{public}d, userId:%{public}d, authType:%{public}d", ret,
333 userId, authType);
334 callback->OnGetExecutorPropertyResult(GENERAL_ERROR, values);
335 return;
336 }
337 if (templateIds.size() == 0) {
338 IAM_LOGE("template id list is required, but templateIds size is 0");
339 callback->OnGetExecutorPropertyResult(NOT_ENROLLED, values);
340 return;
341 }
342 }
343
344 GetPropertyInner(authType, keys, callback, templateIds);
345 }
346
GetPropertyById(uint64_t credentialId,const std::vector<Attributes::AttributeKey> & keys,sptr<GetExecutorPropertyCallbackInterface> & callback)347 void UserAuthService::GetPropertyById(uint64_t credentialId, const std::vector<Attributes::AttributeKey> &keys,
348 sptr<GetExecutorPropertyCallbackInterface> &callback)
349 {
350 IAM_LOGI("start");
351 Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
352 IF_FALSE_LOGE_AND_RETURN(callback != nullptr);
353 Attributes values;
354
355 if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
356 IAM_LOGE("failed to check permission");
357 callback->OnGetExecutorPropertyResult(CHECK_PERMISSION_FAILED, values);
358 return;
359 }
360
361 std::shared_ptr<CredentialInfoInterface> credInfo;
362 std::vector<uint64_t> templateIds;
363 int32_t ret = UserIdmDatabase::Instance().GetCredentialInfoById(credentialId, credInfo);
364 if (ret != SUCCESS) {
365 IAM_LOGE("get credentialInfp fail, ret:%{public}d", ret);
366 callback->OnGetExecutorPropertyResult(ret, values);
367 return;
368 }
369 if (credInfo == nullptr) {
370 IAM_LOGE("credential is nullptr");
371 callback->OnGetExecutorPropertyResult(GENERAL_ERROR, values);
372 return;
373 }
374
375 AuthType authType = credInfo->GetAuthType();
376 templateIds.push_back(credInfo->GetTemplateId());
377 GetPropertyInner(authType, keys, callback, templateIds);
378 }
379
SetProperty(int32_t userId,AuthType authType,const Attributes & attributes,sptr<SetExecutorPropertyCallbackInterface> & callback)380 void UserAuthService::SetProperty(int32_t userId, AuthType authType, const Attributes &attributes,
381 sptr<SetExecutorPropertyCallbackInterface> &callback)
382 {
383 IAM_LOGI("start");
384 Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
385 if (callback == nullptr) {
386 IAM_LOGE("callback is nullptr");
387 return;
388 }
389 if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
390 IAM_LOGE("permission check failed");
391 callback->OnSetExecutorPropertyResult(CHECK_PERMISSION_FAILED);
392 return;
393 }
394
395 std::vector<std::weak_ptr<ResourceNode>> authTypeNodes;
396 GetResourceNodeByTypeAndRole(authType, ALL_IN_ONE, authTypeNodes);
397 if (authTypeNodes.size() != 1) {
398 IAM_LOGE("auth type %{public}d resource node num %{public}zu is not expected",
399 authType, authTypeNodes.size());
400 callback->OnSetExecutorPropertyResult(GENERAL_ERROR);
401 return;
402 }
403
404 auto resourceNode = authTypeNodes[0].lock();
405 if (resourceNode == nullptr) {
406 IAM_LOGE("resourceNode is nullptr");
407 callback->OnSetExecutorPropertyResult(GENERAL_ERROR);
408 return;
409 }
410 int32_t result = resourceNode->SetProperty(attributes);
411 if (result != SUCCESS) {
412 IAM_LOGE("set property failed, result = %{public}d", result);
413 }
414 callback->OnSetExecutorPropertyResult(result);
415 }
416
GetAuthContextCallback(int32_t apiVersion,const std::vector<uint8_t> & challenge,AuthType authType,AuthTrustLevel authTrustLevel,sptr<UserAuthCallbackInterface> & callback)417 std::shared_ptr<ContextCallback> UserAuthService::GetAuthContextCallback(int32_t apiVersion,
418 const std::vector<uint8_t> &challenge, AuthType authType,
419 AuthTrustLevel authTrustLevel, sptr<UserAuthCallbackInterface> &callback)
420 {
421 if (callback == nullptr) {
422 IAM_LOGE("callback is nullptr");
423 return nullptr;
424 }
425 auto contextCallback = ContextCallback::NewInstance(callback, TRACE_AUTH_USER_ALL);
426 if (contextCallback == nullptr) {
427 IAM_LOGE("failed to construct context callback");
428 Attributes extraInfo;
429 callback->OnResult(GENERAL_ERROR, extraInfo);
430 return nullptr;
431 }
432 contextCallback->SetTraceAuthType(authType);
433 contextCallback->SetTraceAuthWidgetType(authType);
434 contextCallback->SetTraceAuthTrustLevel(authTrustLevel);
435 contextCallback->SetTraceSdkVersion(apiVersion);
436 return contextCallback;
437 }
438
CheckAuthPermissionAndParam(int32_t authType,const int32_t & callerType,const std::string & callerName,AuthTrustLevel authTrustLevel)439 int32_t UserAuthService::CheckAuthPermissionAndParam(int32_t authType, const int32_t &callerType,
440 const std::string &callerName, AuthTrustLevel authTrustLevel)
441 {
442 if (!IpcCommon::CheckPermission(*this, ACCESS_BIOMETRIC_PERMISSION)) {
443 IAM_LOGE("failed to check permission");
444 return CHECK_PERMISSION_FAILED;
445 }
446 if (callerType == Security::AccessToken::TOKEN_HAP && (!IpcCommon::CheckForegroundApplication(callerName))) {
447 IAM_LOGE("failed to check foreground application");
448 return CHECK_PERMISSION_FAILED;
449 }
450 if (authType == PIN) {
451 IAM_LOGE("authType not support");
452 return TYPE_NOT_SUPPORT;
453 }
454 if (!CheckAuthTrustLevel(authTrustLevel)) {
455 IAM_LOGE("authTrustLevel is not in correct range");
456 return TRUST_LEVEL_NOT_SUPPORT;
457 }
458 return SUCCESS;
459 }
460
Auth(int32_t apiVersion,const std::vector<uint8_t> & challenge,AuthType authType,AuthTrustLevel authTrustLevel,sptr<UserAuthCallbackInterface> & callback)461 uint64_t UserAuthService::Auth(int32_t apiVersion, const std::vector<uint8_t> &challenge,
462 AuthType authType, AuthTrustLevel authTrustLevel, sptr<UserAuthCallbackInterface> &callback)
463 {
464 IAM_LOGI("start");
465 auto contextCallback = GetAuthContextCallback(apiVersion, challenge, authType, authTrustLevel, callback);
466 if (contextCallback == nullptr) {
467 IAM_LOGE("contextCallback is nullptr");
468 return BAD_CONTEXT_ID;
469 }
470 std::string callerName = "";
471 Attributes extraInfo;
472 int32_t callerType = Security::AccessToken::TOKEN_INVALID;
473 if ((!IpcCommon::GetCallerName(*this, callerName, callerType))) {
474 IAM_LOGE("get bundle name fail");
475 contextCallback->SetTraceAuthFinishReason("UserAuthService Auth GetCallerName fail");
476 contextCallback->OnResult(GENERAL_ERROR, extraInfo);
477 return BAD_CONTEXT_ID;
478 }
479 contextCallback->SetTraceCallerName(callerName);
480 contextCallback->SetTraceCallerType(callerType);
481 int32_t checkRet = CheckAuthPermissionAndParam(authType, callerType, callerName, authTrustLevel);
482 if (checkRet != SUCCESS) {
483 IAM_LOGE("check auth permission and param fail");
484 contextCallback->SetTraceAuthFinishReason("UserAuthService Auth CheckAuthPermissionAndParam fail");
485 contextCallback->OnResult(checkRet, extraInfo);
486 return BAD_CONTEXT_ID;
487 }
488 int32_t userId = INVALID_USER_ID;
489 if (IpcCommon::GetCallingUserId(*this, userId) != SUCCESS) {
490 IAM_LOGE("get callingUserId failed");
491 contextCallback->SetTraceAuthFinishReason("UserAuthService Auth GetCallingUserId fail");
492 contextCallback->OnResult(GENERAL_ERROR, extraInfo);
493 return BAD_CONTEXT_ID;
494 }
495 contextCallback->SetTraceUserId(userId);
496 Authentication::AuthenticationPara para = {};
497 para.tokenId = IpcCommon::GetAccessTokenId(*this);
498 para.userId = userId;
499 para.authType = authType;
500 para.atl = authTrustLevel;
501 para.challenge = std::move(challenge);
502 para.endAfterFirstFail = true;
503 para.callerName = callerName;
504 para.callerType = callerType;
505 para.sdkVersion = apiVersion;
506 para.authIntent = AuthIntent::DEFAULT;
507 para.isOsAccountVerified = IpcCommon::IsOsAccountVerified(userId);
508 return StartAuthContext(apiVersion, para, contextCallback, true);
509 }
510
StartAuthContext(int32_t apiVersion,Authentication::AuthenticationPara para,const std::shared_ptr<ContextCallback> & contextCallback,bool needSubscribeAppState)511 uint64_t UserAuthService::StartAuthContext(int32_t apiVersion, Authentication::AuthenticationPara para,
512 const std::shared_ptr<ContextCallback> &contextCallback, bool needSubscribeAppState)
513 {
514 Attributes extraInfo;
515 auto context = ContextFactory::CreateSimpleAuthContext(para, contextCallback, needSubscribeAppState);
516 if (context == nullptr || !ContextPool::Instance().Insert(context)) {
517 IAM_LOGE("failed to insert context");
518 contextCallback->SetTraceAuthFinishReason("UserAuthService Auth insert context fail");
519 contextCallback->OnResult(GENERAL_ERROR, extraInfo);
520 return BAD_CONTEXT_ID;
521 }
522 contextCallback->SetTraceRequestContextId(context->GetContextId());
523 contextCallback->SetTraceAuthContextId(context->GetContextId());
524 contextCallback->SetCleaner(ContextHelper::Cleaner(context));
525
526 if (!context->Start()) {
527 int32_t errorCode = context->GetLatestError();
528 IAM_LOGE("failed to start auth apiVersion:%{public}d errorCode:%{public}d", apiVersion, errorCode);
529 contextCallback->SetTraceAuthFinishReason("UserAuthService Auth start context fail");
530 contextCallback->OnResult(errorCode, extraInfo);
531 return BAD_CONTEXT_ID;
532 }
533 return context->GetContextId();
534 }
535
StartRemoteAuthInvokerContext(AuthParamInner authParam,RemoteAuthInvokerContextParam & param,const std::shared_ptr<ContextCallback> & contextCallback)536 uint64_t UserAuthService::StartRemoteAuthInvokerContext(AuthParamInner authParam,
537 RemoteAuthInvokerContextParam ¶m, const std::shared_ptr<ContextCallback> &contextCallback)
538 {
539 Attributes extraInfo;
540 std::shared_ptr<Context> context = ContextFactory::CreateRemoteAuthInvokerContext(authParam, param,
541 contextCallback);
542 if (context == nullptr || !ContextPool::Instance().Insert(context)) {
543 IAM_LOGE("failed to insert context");
544 contextCallback->SetTraceAuthFinishReason("UserAuthService StartRemoteAuthInvokerContext insert context fail");
545 contextCallback->OnResult(GENERAL_ERROR, extraInfo);
546 return BAD_CONTEXT_ID;
547 }
548 contextCallback->SetCleaner(ContextHelper::Cleaner(context));
549 contextCallback->SetTraceRequestContextId(context->GetContextId());
550 contextCallback->SetTraceAuthContextId(context->GetContextId());
551
552 if (!context->Start()) {
553 int32_t errorCode = context->GetLatestError();
554 IAM_LOGE("failed to start auth errorCode:%{public}d", errorCode);
555 contextCallback->SetTraceAuthFinishReason("UserAuthService StartRemoteAuthInvokerContext start context fail");
556 contextCallback->OnResult(errorCode, extraInfo);
557 return BAD_CONTEXT_ID;
558 }
559 return context->GetContextId();
560 }
561
CheckAuthPermissionAndParam(AuthType authType,AuthTrustLevel authTrustLevel,const std::shared_ptr<ContextCallback> & contextCallback,Attributes & extraInfo)562 bool UserAuthService::CheckAuthPermissionAndParam(AuthType authType, AuthTrustLevel authTrustLevel,
563 const std::shared_ptr<ContextCallback> &contextCallback, Attributes &extraInfo)
564 {
565 if (!CheckAuthTrustLevel(authTrustLevel)) {
566 IAM_LOGE("authTrustLevel is not in correct range");
567 contextCallback->SetTraceAuthFinishReason("UserAuthService AuthUser CheckAuthTrustLevel fail");
568 contextCallback->OnResult(TRUST_LEVEL_NOT_SUPPORT, extraInfo);
569 return false;
570 }
571 if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
572 IAM_LOGE("failed to check permission");
573 contextCallback->SetTraceAuthFinishReason("UserAuthService AuthUser CheckPermission fail");
574 contextCallback->OnResult(CHECK_PERMISSION_FAILED, extraInfo);
575 return false;
576 }
577 return true;
578 }
579
AuthUser(AuthParamInner & authParam,std::optional<RemoteAuthParam> & remoteAuthParam,sptr<UserAuthCallbackInterface> & callback)580 uint64_t UserAuthService::AuthUser(AuthParamInner &authParam, std::optional<RemoteAuthParam> &remoteAuthParam,
581 sptr<UserAuthCallbackInterface> &callback)
582 {
583 IAM_LOGI("start, %{public}s", GetAuthParamStr(authParam, remoteAuthParam).c_str());
584 Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
585 auto contextCallback = GetAuthContextCallback(INNER_API_VERSION_10000, authParam.challenge, authParam.authType,
586 authParam.authTrustLevel, callback);
587 if (contextCallback == nullptr) {
588 IAM_LOGE("contextCallback is nullptr");
589 return BAD_CONTEXT_ID;
590 }
591 contextCallback->SetTraceIsRemoteAuth(remoteAuthParam.has_value());
592 contextCallback->SetTraceUserId(authParam.userId);
593 Attributes extraInfo;
594 Authentication::AuthenticationPara para = {};
595 if ((!IpcCommon::GetCallerName(*this, para.callerName, para.callerType))) {
596 IAM_LOGE("get caller name fail");
597 contextCallback->SetTraceAuthFinishReason("UserAuthService AuthUser GetCallerName fail");
598 contextCallback->OnResult(GENERAL_ERROR, extraInfo);
599 return BAD_CONTEXT_ID;
600 }
601 contextCallback->SetTraceCallerName(para.callerName);
602 contextCallback->SetTraceCallerType(para.callerType);
603 if (CheckAuthPermissionAndParam(authParam.authType, authParam.authTrustLevel, contextCallback,
604 extraInfo) == false) {
605 return BAD_CONTEXT_ID;
606 }
607 para.tokenId = IpcCommon::GetAccessTokenId(*this);
608 para.userId = authParam.userId;
609 para.authType = authParam.authType;
610 para.atl = authParam.authTrustLevel;
611 para.challenge = authParam.challenge;
612 para.endAfterFirstFail = false;
613 para.sdkVersion = INNER_API_VERSION_10000;
614 para.authIntent = authParam.authIntent;
615 para.isOsAccountVerified = IpcCommon::IsOsAccountVerified(authParam.userId);
616 if (!remoteAuthParam.has_value()) {
617 bool needSubscribeAppState = !IpcCommon::CheckPermission(*this, USER_AUTH_FROM_BACKGROUND);
618 return StartAuthContext(INNER_API_VERSION_10000, para, contextCallback, needSubscribeAppState);
619 }
620
621 ResultCode failReason = GENERAL_ERROR;
622 uint64_t contextId = AuthRemoteUser(authParam, para, remoteAuthParam.value(), contextCallback, failReason);
623 if (contextId == BAD_CONTEXT_ID) {
624 contextCallback->SetTraceAuthFinishReason("UserAuthService AuthRemoteUser fail");
625 contextCallback->OnResult(failReason, extraInfo);
626 return BAD_CONTEXT_ID;
627 }
628
629 IAM_LOGI("success");
630 return contextId;
631 }
632
DoPrepareRemoteAuth(const std::string & networkId)633 int32_t UserAuthService::DoPrepareRemoteAuth(const std::string &networkId)
634 {
635 IAM_LOGI("start");
636
637 std::string udid;
638 bool getUdidRet = DeviceManagerUtil::GetInstance().GetUdidByNetworkId(networkId, udid);
639 IF_FALSE_LOGE_AND_RETURN_VAL(getUdidRet, GENERAL_ERROR);
640
641 auto hdi = HdiWrapper::GetHdiInstance();
642 IF_FALSE_LOGE_AND_RETURN_VAL(hdi != nullptr, GENERAL_ERROR);
643
644 int32_t ret = hdi->PrepareRemoteAuth(udid);
645 IF_FALSE_LOGE_AND_RETURN_VAL(ret == HDF_SUCCESS, GENERAL_ERROR);
646
647 IAM_LOGI("success");
648 return SUCCESS;
649 }
650
PrepareRemoteAuthInner(const std::string & networkId,sptr<UserAuthCallbackInterface> & callback)651 int32_t UserAuthService::PrepareRemoteAuthInner(const std::string &networkId, sptr<UserAuthCallbackInterface> &callback)
652 {
653 if (networkId.empty()) {
654 IAM_LOGE("networkId is empty");
655 return INVALID_PARAMETERS;
656 }
657
658 if (callback == nullptr) {
659 IAM_LOGE("callback is nullptr");
660 return INVALID_PARAMETERS;
661 }
662
663 if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
664 IAM_LOGE("failed to check permission");
665 return CHECK_PERMISSION_FAILED;
666 }
667
668 auto handler = ThreadHandler::GetSingleThreadInstance();
669 IF_FALSE_LOGE_AND_RETURN_VAL(handler != nullptr, GENERAL_ERROR);
670
671 handler->PostTask([networkId, callback]() {
672 Attributes attr;
673
674 auto service = UserAuthService::GetInstance();
675 if (service == nullptr) {
676 IAM_LOGE("service is nullptr");
677 callback->OnResult(GENERAL_ERROR, attr);
678 return;
679 }
680
681 int32_t ret = service->DoPrepareRemoteAuth(networkId);
682 if (ret != SUCCESS) {
683 IAM_LOGE("failed to prepare remote auth");
684 }
685
686 callback->OnResult(ret, attr);
687 });
688
689 return SUCCESS;
690 }
691
PrepareRemoteAuth(const std::string & networkId,sptr<UserAuthCallbackInterface> & callback)692 int32_t UserAuthService::PrepareRemoteAuth(const std::string &networkId, sptr<UserAuthCallbackInterface> &callback)
693 {
694 IAM_LOGI("start");
695 Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
696 if (callback == nullptr) {
697 IAM_LOGE("callback is nullptr");
698 return INVALID_PARAMETERS;
699 }
700
701 int32_t ret = PrepareRemoteAuthInner(networkId, callback);
702 if (ret != SUCCESS) {
703 IAM_LOGE("failed to prepare remote auth");
704 Attributes attr;
705 callback->OnResult(ret, attr);
706 }
707
708 IAM_LOGI("end");
709 return SUCCESS;
710 }
711
AuthRemoteUser(AuthParamInner & authParam,Authentication::AuthenticationPara & para,RemoteAuthParam & remoteAuthParam,const std::shared_ptr<ContextCallback> & contextCallback,ResultCode & failReason)712 uint64_t UserAuthService::AuthRemoteUser(AuthParamInner &authParam, Authentication::AuthenticationPara ¶,
713 RemoteAuthParam &remoteAuthParam, const std::shared_ptr<ContextCallback> &contextCallback, ResultCode &failReason)
714 {
715 IAM_LOGI("start");
716 failReason = GENERAL_ERROR;
717
718 if (para.authType != PIN) {
719 IAM_LOGE("Remote auth only support pin auth");
720 failReason = INVALID_PARAMETERS;
721 return BAD_CONTEXT_ID;
722 }
723
724 if (authParam.userId == INVALID_USER_ID) {
725 IAM_LOGE("userid must be set for remote auth");
726 failReason = INVALID_PARAMETERS;
727 return BAD_CONTEXT_ID;
728 }
729
730 std::string localNetworkId;
731 bool getNetworkIdRet = DeviceManagerUtil::GetInstance().GetLocalDeviceNetWorkId(localNetworkId);
732 IF_FALSE_LOGE_AND_RETURN_VAL(getNetworkIdRet, BAD_CONTEXT_ID);
733
734 bool completeRet = CompleteRemoteAuthParam(remoteAuthParam, localNetworkId);
735 if (!completeRet) {
736 IAM_LOGE("failed to complete remote auth param");
737 failReason = INVALID_PARAMETERS;
738 return BAD_CONTEXT_ID;
739 }
740
741 if (remoteAuthParam.collectorTokenId.has_value()) {
742 para.collectorTokenId = remoteAuthParam.collectorTokenId.value();
743 } else {
744 para.collectorTokenId = para.tokenId;
745 }
746
747 if (remoteAuthParam.collectorNetworkId.value() == localNetworkId) {
748 RemoteAuthInvokerContextParam remoteAuthInvokerContextParam;
749 remoteAuthInvokerContextParam.connectionName = "";
750 remoteAuthInvokerContextParam.verifierNetworkId = remoteAuthParam.verifierNetworkId.value();
751 remoteAuthInvokerContextParam.collectorNetworkId = remoteAuthParam.collectorNetworkId.value();
752 remoteAuthInvokerContextParam.tokenId = para.tokenId;
753 remoteAuthInvokerContextParam.collectorTokenId = para.collectorTokenId;
754 remoteAuthInvokerContextParam.callerName = para.callerName;
755 remoteAuthInvokerContextParam.callerType = para.callerType;
756 IAM_LOGI("start remote auth invoker context");
757 return StartRemoteAuthInvokerContext(authParam, remoteAuthInvokerContextParam, contextCallback);
758 }
759
760 RemoteAuthContextParam remoteAuthContextParam;
761 remoteAuthContextParam.authType = authParam.authType;
762 remoteAuthContextParam.connectionName = "";
763 remoteAuthContextParam.collectorNetworkId = remoteAuthParam.collectorNetworkId.value();
764 remoteAuthContextParam.executorInfoMsg = {};
765 int32_t dummyLastError = 0;
766 IAM_LOGI("start remote auth context");
767 return RemoteAuthService::GetInstance().StartRemoteAuthContext(
768 para, remoteAuthContextParam, contextCallback, dummyLastError);
769 }
770
Identify(const std::vector<uint8_t> & challenge,AuthType authType,sptr<UserAuthCallbackInterface> & callback)771 uint64_t UserAuthService::Identify(const std::vector<uint8_t> &challenge, AuthType authType,
772 sptr<UserAuthCallbackInterface> &callback)
773 {
774 IAM_LOGI("start");
775 Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
776
777 if (callback == nullptr) {
778 IAM_LOGE("callback is nullptr");
779 return BAD_CONTEXT_ID;
780 }
781 Attributes extraInfo;
782 auto contextCallback = ContextCallback::NewInstance(callback, TRACE_IDENTIFY);
783 if (contextCallback == nullptr) {
784 IAM_LOGE("failed to construct context callback");
785 callback->OnResult(GENERAL_ERROR, extraInfo);
786 return BAD_CONTEXT_ID;
787 }
788 if (authType == PIN) {
789 IAM_LOGE("type not support %{public}d", authType);
790 contextCallback->SetTraceAuthFinishReason("UserAuthService Identify IsAuthTypeEnable fail");
791 contextCallback->OnResult(TYPE_NOT_SUPPORT, extraInfo);
792 return BAD_CONTEXT_ID;
793 }
794 if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
795 IAM_LOGE("failed to check permission");
796 contextCallback->SetTraceAuthFinishReason("UserAuthService Identify CheckPermission fail");
797 contextCallback->OnResult(CHECK_PERMISSION_FAILED, extraInfo);
798 return BAD_CONTEXT_ID;
799 }
800
801 Identification::IdentificationPara para = {};
802 para.tokenId = IpcCommon::GetAccessTokenId(*this);
803 para.authType = authType;
804 para.challenge = std::move(challenge);
805 auto context = ContextFactory::CreateIdentifyContext(para, contextCallback);
806 if (!ContextPool::Instance().Insert(context)) {
807 IAM_LOGE("failed to insert context");
808 contextCallback->SetTraceAuthFinishReason("UserAuthService Identify insert context fail");
809 contextCallback->OnResult(GENERAL_ERROR, extraInfo);
810 return BAD_CONTEXT_ID;
811 }
812
813 contextCallback->SetCleaner(ContextHelper::Cleaner(context));
814
815 if (!context->Start()) {
816 IAM_LOGE("failed to start identify");
817 contextCallback->SetTraceAuthFinishReason("UserAuthService Identify start context fail");
818 contextCallback->OnResult(context->GetLatestError(), extraInfo);
819 return BAD_CONTEXT_ID;
820 }
821 return context->GetContextId();
822 }
823
CancelAuthOrIdentify(uint64_t contextId,int32_t cancelReason)824 int32_t UserAuthService::CancelAuthOrIdentify(uint64_t contextId, int32_t cancelReason)
825 {
826 IAM_LOGI("start");
827 Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
828 bool checkRet = !IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION) &&
829 !IpcCommon::CheckPermission(*this, ACCESS_BIOMETRIC_PERMISSION);
830 if (checkRet) {
831 IAM_LOGE("failed to check permission");
832 return CHECK_PERMISSION_FAILED;
833 }
834 auto context = ContextPool::Instance().Select(contextId).lock();
835 if (context == nullptr) {
836 IAM_LOGE("context not exist");
837 return GENERAL_ERROR;
838 }
839
840 if (context->GetTokenId() != IpcCommon::GetAccessTokenId(*this)) {
841 IAM_LOGE("failed to check tokenId");
842 return INVALID_CONTEXT_ID;
843 }
844
845 if (cancelReason == CancelReason::MODAL_CREATE_ERROR || cancelReason == CancelReason::MODAL_RUN_ERROR) {
846 IAM_LOGE("widget modal fault");
847 UserIam::UserAuth::ReportSystemFault(Common::GetNowTimeString(), "AuthWidget");
848 }
849
850 if (!context->Stop()) {
851 IAM_LOGE("failed to cancel auth or identify");
852 return context->GetLatestError();
853 }
854
855 return SUCCESS;
856 }
857
GetVersion(int32_t & version)858 int32_t UserAuthService::GetVersion(int32_t &version)
859 {
860 IAM_LOGI("start");
861 version = MINIMUM_VERSION;
862 bool checkRet = !IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION) &&
863 !IpcCommon::CheckPermission(*this, ACCESS_BIOMETRIC_PERMISSION);
864 if (checkRet) {
865 IAM_LOGE("failed to check permission");
866 return CHECK_PERMISSION_FAILED;
867 }
868 version = CURRENT_VERSION;
869 return SUCCESS;
870 }
871
CheckAuthWidgetType(const std::vector<AuthType> & authType)872 int32_t UserAuthService::CheckAuthWidgetType(const std::vector<AuthType> &authType)
873 {
874 if (authType.empty() || (authType.size() > MAX_AUTH_TYPE_SIZE)) {
875 IAM_LOGE("invalid authType size:%{public}zu", authType.size());
876 return INVALID_PARAMETERS;
877 }
878 for (auto &type : authType) {
879 if ((type != AuthType::PIN) && (type != AuthType::FACE) && (type != AuthType::FINGERPRINT) &&
880 (type != AuthType::PRIVATE_PIN)) {
881 IAM_LOGE("unsupport auth type %{public}d", type);
882 return TYPE_NOT_SUPPORT;
883 }
884 }
885 std::set<AuthType> typeChecker(authType.begin(), authType.end());
886 if (typeChecker.size() != authType.size()) {
887 IAM_LOGE("duplicate auth type");
888 return INVALID_PARAMETERS;
889 }
890 bool hasPin = false;
891 bool hasPrivatePin = false;
892 for (const auto &iter : authType) {
893 if (iter == AuthType::PIN) {
894 hasPin = true;
895 } else if (iter == AuthType::PRIVATE_PIN) {
896 hasPrivatePin = true;
897 }
898 }
899 if (hasPin && hasPrivatePin) {
900 IAM_LOGE("pin and private pin not support");
901 return INVALID_PARAMETERS;
902 }
903 return SUCCESS;
904 }
905
CheckSingeFaceOrFinger(const std::vector<AuthType> & authType)906 bool UserAuthService::CheckSingeFaceOrFinger(const std::vector<AuthType> &authType)
907 {
908 return std::all_of(authType.begin(), authType.end(), [](AuthType type) {
909 return type == AuthType::FACE || type == AuthType::FINGERPRINT;
910 });
911 }
912
CheckPrivatePinEnroll(const std::vector<AuthType> & authType,std::vector<AuthType> & validType)913 bool UserAuthService::CheckPrivatePinEnroll(const std::vector<AuthType> &authType, std::vector<AuthType> &validType)
914 {
915 bool hasPrivatePin = false;
916 for (auto &iter : authType) {
917 if (iter == AuthType::PRIVATE_PIN) {
918 hasPrivatePin = true;
919 break;
920 }
921 }
922 if (!hasPrivatePin) {
923 return true;
924 }
925 const size_t sizeTwo = 2;
926 bool hasFace = false;
927 bool hasFinger = false;
928 for (const auto &iter : validType) {
929 if (iter == AuthType::FACE) {
930 hasFace = true;
931 } else if (iter == AuthType::FINGERPRINT) {
932 hasFinger = true;
933 }
934 if (hasFace && hasFinger) {
935 break;
936 }
937 }
938 if (validType.size() == sizeTwo && hasFace && hasFinger) {
939 return false;
940 }
941 return true;
942 }
943
CheckCallerPermissionForPrivatePin(const AuthParamInner & authParam)944 int32_t UserAuthService::CheckCallerPermissionForPrivatePin(const AuthParamInner &authParam)
945 {
946 bool hasPrivatePin = false;
947 for (auto &iter : authParam.authTypes) {
948 if (iter == AuthType::PRIVATE_PIN) {
949 hasPrivatePin = true;
950 break;
951 }
952 }
953 if (!hasPrivatePin) {
954 return SUCCESS;
955 }
956 if (IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
957 return SUCCESS;
958 }
959 if (IpcCommon::CheckPermission(*this, IS_SYSTEM_APP)) {
960 return SUCCESS;
961 }
962 IAM_LOGE("CheckPermission failed");
963 return CHECK_PERMISSION_FAILED;
964 }
965
CheckCallerPermissionForUserId(const AuthParamInner & authParam)966 int32_t UserAuthService::CheckCallerPermissionForUserId(const AuthParamInner &authParam)
967 {
968 // inner api caller
969 if (IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
970 return SUCCESS;
971 }
972 // native api caller
973 int32_t userId = INVALID_USER_ID;
974 if (IpcCommon::GetCallingUserId(*this, userId) != SUCCESS) {
975 IAM_LOGE("failed to get callingUserId");
976 return GENERAL_ERROR;
977 }
978 if (IpcCommon::CheckPermission(*this, ACCESS_BIOMETRIC_PERMISSION) &&
979 (IpcCommon::CheckPermission(*this, IS_SYSTEM_APP) || authParam.userId == userId)) {
980 return SUCCESS;
981 }
982 IAM_LOGE("CheckPermission failed");
983 return CHECK_PERMISSION_FAILED;
984 }
985
CheckAuthPermissionAndParam(const AuthParamInner & authParam,const WidgetParamInner & widgetParam,bool isBackgroundApplication)986 int32_t UserAuthService::CheckAuthPermissionAndParam(const AuthParamInner &authParam,
987 const WidgetParamInner &widgetParam, bool isBackgroundApplication)
988 {
989 int32_t checkRet = CheckWindowMode(widgetParam);
990 if (checkRet != SUCCESS) {
991 IAM_LOGE("CheckWindowMode failed");
992 return checkRet;
993 }
994 if (CheckCallerPermissionForPrivatePin(authParam) != SUCCESS) {
995 IAM_LOGE("CheckCallerPermissionForPrivatePin failed");
996 return CHECK_PERMISSION_FAILED;
997 }
998 if (!authParam.isUserIdSpecified && !IpcCommon::CheckPermission(*this, ACCESS_BIOMETRIC_PERMISSION)) {
999 IAM_LOGE("CheckPermission failed");
1000 return CHECK_PERMISSION_FAILED;
1001 }
1002 if (authParam.isUserIdSpecified && CheckCallerPermissionForUserId(authParam) != SUCCESS) {
1003 IAM_LOGE("CheckPermission failed");
1004 return CHECK_PERMISSION_FAILED;
1005 }
1006 if (isBackgroundApplication && (!IpcCommon::CheckPermission(*this, USER_AUTH_FROM_BACKGROUND))) {
1007 IAM_LOGE("failed to check foreground application");
1008 return CHECK_PERMISSION_FAILED;
1009 }
1010 int32_t ret = CheckAuthWidgetType(authParam.authTypes);
1011 if (ret != SUCCESS) {
1012 IAM_LOGE("CheckAuthWidgetType fail.");
1013 return ret;
1014 }
1015 if (!CheckAuthTrustLevel(authParam.authTrustLevel)) {
1016 IAM_LOGE("authTrustLevel is not in correct range");
1017 return ResultCode::TRUST_LEVEL_NOT_SUPPORT;
1018 }
1019 if (widgetParam.navigationButtonText.empty()) {
1020 static const size_t authTypeTwo = 2;
1021 static const size_t authType0 = 0;
1022 static const size_t authType1 = 1;
1023 std::vector<AuthType> authType = authParam.authTypes;
1024 if (((authType.size() == authTypeTwo) &&
1025 (authType[authType0] == AuthType::FACE) && (authType[authType1] == AuthType::FINGERPRINT)) ||
1026 ((authType.size() == authTypeTwo) &&
1027 (authType[authType0] == AuthType::FINGERPRINT) && (authType[authType1] == AuthType::FACE))) {
1028 IAM_LOGE("only face and finger not support");
1029 return INVALID_PARAMETERS;
1030 }
1031 }
1032 if (widgetParam.title.empty()) {
1033 IAM_LOGE("title is empty");
1034 return INVALID_PARAMETERS;
1035 }
1036 return SUCCESS;
1037 }
1038
CheckWindowMode(const WidgetParamInner & widgetParam)1039 int32_t UserAuthService::CheckWindowMode(const WidgetParamInner &widgetParam)
1040 {
1041 if (!IpcCommon::CheckPermission(*this, IS_SYSTEM_APP) &&
1042 (widgetParam.windowMode == WindowModeType::NONE_INTERRUPTION_DIALOG_BOX)) {
1043 IAM_LOGE("the caller is not a system application.");
1044 return CHECK_SYSTEM_APP_FAILED;
1045 }
1046 if (!IpcCommon::CheckPermission(*this, IS_SYSTEM_APP) &&
1047 (widgetParam.windowMode != WindowModeType::UNKNOWN_WINDOW_MODE)) {
1048 IAM_LOGE("normal app can't set window mode.");
1049 return INVALID_PARAMETERS;
1050 }
1051 return SUCCESS;
1052 }
1053
StartWidgetContext(const std::shared_ptr<ContextCallback> & contextCallback,const AuthParamInner & authParam,const WidgetParamInner & widgetParam,std::vector<AuthType> & validType,ContextFactory::AuthWidgetContextPara & para)1054 uint64_t UserAuthService::StartWidgetContext(const std::shared_ptr<ContextCallback> &contextCallback,
1055 const AuthParamInner &authParam, const WidgetParamInner &widgetParam, std::vector<AuthType> &validType,
1056 ContextFactory::AuthWidgetContextPara ¶)
1057 {
1058 Attributes extraInfo;
1059 para.tokenId = IpcCommon::GetAccessTokenId(*this);
1060 para.isOsAccountVerified = IpcCommon::IsOsAccountVerified(para.userId);
1061 if (!AuthWidgetHelper::InitWidgetContextParam(authParam, validType, widgetParam, para)) {
1062 IAM_LOGE("init widgetContext failed");
1063 contextCallback->SetTraceAuthFinishReason("UserAuthService InitWidgetContextParam fail");
1064 contextCallback->OnResult(ResultCode::GENERAL_ERROR, extraInfo);
1065 return BAD_CONTEXT_ID;
1066 }
1067 auto context = ContextFactory::CreateWidgetContext(para, contextCallback);
1068 if (context == nullptr || !Insert2ContextPool(context)) {
1069 contextCallback->SetTraceAuthFinishReason("UserAuthService AuthWidget insert context fail");
1070 contextCallback->OnResult(ResultCode::GENERAL_ERROR, extraInfo);
1071 return BAD_CONTEXT_ID;
1072 }
1073 contextCallback->SetTraceRequestContextId(context->GetContextId());
1074 contextCallback->SetCleaner(ContextHelper::Cleaner(context));
1075 if (!context->Start()) {
1076 int32_t errorCode = context->GetLatestError();
1077 IAM_LOGE("start widget context fail %{public}d", errorCode);
1078 contextCallback->SetTraceAuthFinishReason("UserAuthService AuthWidget start context fail");
1079 contextCallback->OnResult(errorCode, extraInfo);
1080 return BAD_CONTEXT_ID;
1081 }
1082 return context->GetContextId();
1083 }
1084
CheckValidSolution(int32_t userId,const AuthParamInner & authParam,const WidgetParamInner & widgetParam,std::vector<AuthType> & validType)1085 int32_t UserAuthService::CheckValidSolution(int32_t userId, const AuthParamInner &authParam,
1086 const WidgetParamInner &widgetParam, std::vector<AuthType> &validType)
1087 {
1088 int32_t ret = AuthWidgetHelper::CheckValidSolution(
1089 userId, authParam.authTypes, authParam.authTrustLevel, validType);
1090 if (ret != SUCCESS) {
1091 IAM_LOGE("CheckValidSolution fail %{public}d", ret);
1092 return ret;
1093 }
1094 if (!widgetParam.navigationButtonText.empty() && !CheckSingeFaceOrFinger(validType)) {
1095 IAM_LOGE("navigationButtonText check fail, validType.size:%{public}zu", validType.size());
1096 return INVALID_PARAMETERS;
1097 }
1098 if (widgetParam.windowMode == FULLSCREEN && CheckSingeFaceOrFinger(validType)) {
1099 IAM_LOGE("Single fingerprint or single face does not support full screen");
1100 return INVALID_PARAMETERS;
1101 }
1102 if (!CheckPrivatePinEnroll(authParam.authTypes, validType)) {
1103 IAM_LOGE("check privatePin enroll error");
1104 return INVALID_PARAMETERS;
1105 }
1106 if (!IpcCommon::IsOsAccountVerified(userId)) {
1107 IAM_LOGI("auth userId: %{public}u, biometric authentication has been filtered.", userId);
1108 validType.erase(std::remove_if(validType.begin(), validType.end(), [](AuthType authType) {
1109 return authType != AuthType::PIN && authType != AuthType::PRIVATE_PIN;
1110 }), validType.end());
1111 }
1112 if (validType.empty()) {
1113 IAM_LOGE("validType size is 0");
1114 return TYPE_NOT_SUPPORT;
1115 }
1116 return SUCCESS;
1117 }
1118
GetCallerInfo(bool isUserIdSpecified,int32_t userId,ContextFactory::AuthWidgetContextPara & para,std::shared_ptr<ContextCallback> & contextCallback)1119 int32_t UserAuthService::GetCallerInfo(bool isUserIdSpecified, int32_t userId,
1120 ContextFactory::AuthWidgetContextPara ¶, std::shared_ptr<ContextCallback> &contextCallback)
1121 {
1122 static_cast<void>(IpcCommon::GetCallerName(*this, para.callerName, para.callerType));
1123 contextCallback->SetTraceCallerName(para.callerName);
1124 contextCallback->SetTraceCallerType(para.callerType);
1125 static_cast<void>(IpcCommon::GetCallingAppID(*this, para.callingAppID));
1126
1127 if (para.sdkVersion < INNER_API_VERSION_10000 && para.callerType == Security::AccessToken::TOKEN_HAP &&
1128 (!IpcCommon::CheckForegroundApplication(para.callerName))) {
1129 para.isBackgroundApplication = true;
1130 }
1131 contextCallback->SetTraceIsBackgroundApplication(para.isBackgroundApplication);
1132
1133 if (isUserIdSpecified) {
1134 para.userId = userId;
1135 contextCallback->SetTraceUserId(para.userId);
1136 return SUCCESS;
1137 }
1138 if (IpcCommon::GetCallingUserId(*this, para.userId) != SUCCESS) {
1139 IAM_LOGE("get callingUserId failed");
1140 return GENERAL_ERROR;
1141 }
1142 contextCallback->SetTraceUserId(para.userId);
1143 return SUCCESS;
1144 }
1145
ProcessPinExpired(int32_t ret,const AuthParamInner & authParam,std::vector<AuthType> & validType,ContextFactory::AuthWidgetContextPara & para)1146 void UserAuthService::ProcessPinExpired(int32_t ret, const AuthParamInner &authParam,
1147 std::vector<AuthType> &validType, ContextFactory::AuthWidgetContextPara ¶)
1148 {
1149 if (ret != PIN_EXPIRED) {
1150 return;
1151 }
1152 para.isPinExpired = true;
1153 bool hasPrivatePin = false;
1154 for (auto &iter : authParam.authTypes) {
1155 if (iter == AuthType::PRIVATE_PIN) {
1156 hasPrivatePin = true;
1157 break;
1158 }
1159 }
1160 if (hasPrivatePin) {
1161 validType.clear();
1162 validType.emplace_back(AuthType::PRIVATE_PIN);
1163 } else {
1164 validType.emplace_back(AuthType::PIN);
1165 }
1166 }
1167
AuthWidget(int32_t apiVersion,const AuthParamInner & authParam,const WidgetParamInner & widgetParam,sptr<UserAuthCallbackInterface> & callback,sptr<ModalCallbackInterface> & modalCallback)1168 uint64_t UserAuthService::AuthWidget(int32_t apiVersion, const AuthParamInner &authParam,
1169 const WidgetParamInner &widgetParam, sptr<UserAuthCallbackInterface> &callback,
1170 sptr<ModalCallbackInterface> &modalCallback)
1171 {
1172 IAM_LOGI("start %{public}d authTrustLevel:%{public}u", apiVersion, authParam.authTrustLevel);
1173 auto contextCallback = GetAuthContextCallback(apiVersion, authParam, widgetParam, callback);
1174 if (contextCallback == nullptr) {
1175 IAM_LOGE("contextCallback is nullptr");
1176 return BAD_CONTEXT_ID;
1177 }
1178 ContextFactory::AuthWidgetContextPara para;
1179 para.sdkVersion = apiVersion;
1180 Attributes extraInfo;
1181 int32_t checkRet = GetCallerInfo(authParam.isUserIdSpecified, authParam.userId, para, contextCallback);
1182 if (checkRet != SUCCESS) {
1183 contextCallback->SetTraceAuthFinishReason("UserAuthService AuthWidget GetCallerInfo fail");
1184 contextCallback->OnResult(checkRet, extraInfo);
1185 return BAD_CONTEXT_ID;
1186 }
1187 checkRet = CheckAuthPermissionAndParam(authParam, widgetParam, para.isBackgroundApplication);
1188 if (checkRet != SUCCESS) {
1189 IAM_LOGE("check permission and auth widget param failed");
1190 contextCallback->SetTraceAuthFinishReason("UserAuthService AuthWidget CheckAuthPermissionAndParam fail");
1191 contextCallback->OnResult(checkRet, extraInfo);
1192 return BAD_CONTEXT_ID;
1193 }
1194
1195 if (AuthWidgetHelper::CheckReuseUnlockResult(para, authParam, extraInfo) == SUCCESS) {
1196 IAM_LOGE("check reuse unlock result success");
1197 contextCallback->SetTraceAuthFinishReason("UserAuthService AuthWidget CheckReuseUnlockResult success");
1198 contextCallback->OnResult(SUCCESS, extraInfo);
1199 return REUSE_AUTH_RESULT_CONTEXT_ID;
1200 }
1201 std::vector<AuthType> validType;
1202 checkRet = CheckValidSolution(para.userId, authParam, widgetParam, validType);
1203 if (checkRet != SUCCESS && checkRet != PIN_EXPIRED) {
1204 IAM_LOGE("check valid solution failed");
1205 contextCallback->SetTraceAuthFinishReason("UserAuthService AuthWidget CheckValidSolution fail");
1206 contextCallback->OnResult(checkRet, extraInfo);
1207 return BAD_CONTEXT_ID;
1208 }
1209 ProcessPinExpired(checkRet, authParam, validType, para);
1210 ProcessWidgetSessionExclusive();
1211 if (modalCallback != nullptr && widgetParam.hasContext) {
1212 WidgetClient::Instance().SetModalCallback(modalCallback);
1213 }
1214 return StartWidgetContext(contextCallback, authParam, widgetParam, validType, para);
1215 }
1216
ProcessWidgetSessionExclusive()1217 void UserAuthService::ProcessWidgetSessionExclusive()
1218 {
1219 auto contextList = ContextPool::Instance().Select(ContextType::WIDGET_AUTH_CONTEXT);
1220 for (const auto &context : contextList) {
1221 if (auto ctx = context.lock(); ctx != nullptr) {
1222 IAM_LOGE("widget session exclusive, force stop the old context ****%{public}hx",
1223 static_cast<uint16_t>(ctx->GetContextId()));
1224 ctx->Stop();
1225 }
1226 }
1227 }
1228
Insert2ContextPool(const std::shared_ptr<Context> & context)1229 bool UserAuthService::Insert2ContextPool(const std::shared_ptr<Context> &context)
1230 {
1231 bool ret = false;
1232 const int32_t retryTimes = 3;
1233 for (auto i = 0; i < retryTimes; i++) {
1234 ret = ContextPool::Instance().Insert(context);
1235 if (ret) {
1236 break;
1237 }
1238 }
1239 IAM_LOGI("insert context to pool, retry %{public}d times", retryTimes);
1240 return ret;
1241 }
1242
GetAuthContextCallback(int32_t apiVersion,const AuthParamInner & authParam,const WidgetParamInner & widgetParam,sptr<UserAuthCallbackInterface> & callback)1243 std::shared_ptr<ContextCallback> UserAuthService::GetAuthContextCallback(int32_t apiVersion,
1244 const AuthParamInner &authParam, const WidgetParamInner &widgetParam, sptr<UserAuthCallbackInterface> &callback)
1245 {
1246 if (callback == nullptr) {
1247 IAM_LOGE("callback is nullptr");
1248 return nullptr;
1249 }
1250 auto contextCallback = ContextCallback::NewInstance(callback, TRACE_AUTH_USER_BEHAVIOR);
1251 if (contextCallback == nullptr) {
1252 IAM_LOGE("failed to construct context callback");
1253 Attributes extraInfo;
1254 callback->OnResult(ResultCode::GENERAL_ERROR, extraInfo);
1255 return nullptr;
1256 }
1257 contextCallback->SetTraceSdkVersion(apiVersion);
1258 contextCallback->SetTraceAuthTrustLevel(authParam.authTrustLevel);
1259
1260 uint32_t authWidgetType = 0;
1261 for (const auto authType : authParam.authTypes) {
1262 authWidgetType |= static_cast<uint32_t>(authType);
1263 }
1264 static const uint32_t bitWindowMode = 0x40000000;
1265 if (widgetParam.windowMode == FULLSCREEN) {
1266 authWidgetType |= bitWindowMode;
1267 }
1268 static const uint32_t bitNavigation = 0x80000000;
1269 if (!widgetParam.navigationButtonText.empty()) {
1270 authWidgetType |= bitNavigation;
1271 }
1272 IAM_LOGI("SetTraceAuthWidgetType %{public}08x", authWidgetType);
1273 contextCallback->SetTraceAuthWidgetType(authWidgetType);
1274 uint32_t traceReuseMode = 0;
1275 uint64_t traceReuseDuration = 0;
1276 if (authParam.reuseUnlockResult.isReuse) {
1277 traceReuseMode = authParam.reuseUnlockResult.reuseMode;
1278 traceReuseDuration = authParam.reuseUnlockResult.reuseDuration;
1279 }
1280 contextCallback->SetTraceReuseUnlockResultMode(traceReuseMode);
1281 contextCallback->SetTraceReuseUnlockResultDuration(traceReuseDuration);
1282 return contextCallback;
1283 }
1284
Notice(NoticeType noticeType,const std::string & eventData)1285 int32_t UserAuthService::Notice(NoticeType noticeType, const std::string &eventData)
1286 {
1287 IAM_LOGI("start");
1288 if (!IpcCommon::CheckPermission(*this, IS_SYSTEM_APP)) {
1289 IAM_LOGE("the caller is not a system application");
1290 return ResultCode::CHECK_SYSTEM_APP_FAILED;
1291 }
1292
1293 if (!IpcCommon::CheckPermission(*this, SUPPORT_USER_AUTH)) {
1294 IAM_LOGE("failed to check permission");
1295 return ResultCode::CHECK_PERMISSION_FAILED;
1296 }
1297 return WidgetClient::Instance().OnNotice(noticeType, eventData);
1298 }
1299
RegisterWidgetCallback(int32_t version,sptr<WidgetCallbackInterface> & callback)1300 int32_t UserAuthService::RegisterWidgetCallback(int32_t version, sptr<WidgetCallbackInterface> &callback)
1301 {
1302 if (!IpcCommon::CheckPermission(*this, IS_SYSTEM_APP)) {
1303 IAM_LOGE("the caller is not a system application");
1304 return ResultCode::CHECK_SYSTEM_APP_FAILED;
1305 }
1306
1307 if (!IpcCommon::CheckPermission(*this, SUPPORT_USER_AUTH)) {
1308 IAM_LOGE("CheckPermission failed, no permission");
1309 return ResultCode::CHECK_PERMISSION_FAILED;
1310 }
1311
1312 uint32_t tokenId = IpcCommon::GetTokenId(*this);
1313 IAM_LOGE("RegisterWidgetCallback tokenId %{public}s", GET_MASKED_STRING(tokenId).c_str());
1314
1315 int32_t curVersion = std::stoi(NOTICE_VERSION_STR);
1316 if (version != curVersion) {
1317 return ResultCode::INVALID_PARAMETERS;
1318 }
1319 if (callback == nullptr) {
1320 IAM_LOGE("callback is nullptr");
1321 return ResultCode::INVALID_PARAMETERS;
1322 }
1323 WidgetClient::Instance().SetWidgetCallback(callback);
1324 WidgetClient::Instance().SetAuthTokenId(tokenId);
1325 return ResultCode::SUCCESS;
1326 }
1327
GetEnrolledState(int32_t apiVersion,AuthType authType,EnrolledState & enrolledState)1328 int32_t UserAuthService::GetEnrolledState(int32_t apiVersion, AuthType authType,
1329 EnrolledState &enrolledState)
1330 {
1331 IAM_LOGI("start");
1332
1333 if (!IpcCommon::CheckPermission(*this, ACCESS_BIOMETRIC_PERMISSION)) {
1334 IAM_LOGE("failed to check permission");
1335 return CHECK_PERMISSION_FAILED;
1336 }
1337
1338 if (apiVersion < API_VERSION_12) {
1339 IAM_LOGE("failed to check apiVersion");
1340 return TYPE_NOT_SUPPORT;
1341 }
1342
1343 int32_t userId = INVALID_USER_ID;
1344 if (IpcCommon::GetCallingUserId(*this, userId) != SUCCESS) {
1345 IAM_LOGE("failed to get callingUserId");
1346 return GENERAL_ERROR;
1347 }
1348
1349 auto hdi = HdiWrapper::GetHdiInstance();
1350 if (hdi == nullptr) {
1351 IAM_LOGE("hdi interface is nullptr");
1352 return GENERAL_ERROR;
1353 }
1354 HdiEnrolledState hdiEnrolledState = {};
1355 int32_t result = hdi->GetEnrolledState(userId, static_cast<HdiAuthType>(authType), hdiEnrolledState);
1356 if (result != SUCCESS) {
1357 IAM_LOGE("failed to get enrolled state,userId:%{public}d authType:%{public}d", userId, authType);
1358 return result;
1359 }
1360 enrolledState.credentialCount = hdiEnrolledState.credentialCount;
1361 enrolledState.credentialDigest = hdiEnrolledState.credentialDigest;
1362 if (apiVersion < INNER_API_VERSION_10000) {
1363 enrolledState.credentialDigest = hdiEnrolledState.credentialDigest & UINT16_MAX;
1364 }
1365 return SUCCESS;
1366 }
1367
CheckAuthTypeIsValid(std::vector<AuthType> authType)1368 bool UserAuthService::CheckAuthTypeIsValid(std::vector<AuthType> authType)
1369 {
1370 if (authType.empty()) {
1371 return false;
1372 }
1373 for (const auto &iter : authType) {
1374 if (iter != AuthType::PIN && iter != AuthType::FACE && iter != AuthType::FINGERPRINT &&
1375 iter != AuthType::PRIVATE_PIN) {
1376 return false;
1377 }
1378 }
1379 return true;
1380 }
1381
RegistUserAuthSuccessEventListener(const std::vector<AuthType> & authType,const sptr<AuthEventListenerInterface> & listener)1382 int32_t UserAuthService::RegistUserAuthSuccessEventListener(const std::vector<AuthType> &authType,
1383 const sptr<AuthEventListenerInterface> &listener)
1384 {
1385 IAM_LOGI("start");
1386 Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
1387 IF_FALSE_LOGE_AND_RETURN_VAL(listener != nullptr, INVALID_PARAMETERS);
1388
1389 if (!CheckAuthTypeIsValid(authType)) {
1390 IAM_LOGE("failed to check authType");
1391 return INVALID_PARAMETERS;
1392 }
1393
1394 if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
1395 IAM_LOGE("failed to check permission");
1396 return CHECK_PERMISSION_FAILED;
1397 }
1398
1399 int32_t result = AuthEventListenerManager::GetInstance().RegistUserAuthSuccessEventListener(authType, listener);
1400 if (result != SUCCESS) {
1401 IAM_LOGE("failed to regist auth event listener");
1402 return result;
1403 }
1404
1405 return SUCCESS;
1406 }
1407
UnRegistUserAuthSuccessEventListener(const sptr<AuthEventListenerInterface> & listener)1408 int32_t UserAuthService::UnRegistUserAuthSuccessEventListener(
1409 const sptr<AuthEventListenerInterface> &listener)
1410 {
1411 IAM_LOGI("start");
1412 Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
1413 IF_FALSE_LOGE_AND_RETURN_VAL(listener != nullptr, INVALID_PARAMETERS);
1414
1415 if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION)) {
1416 IAM_LOGE("failed to check permission");
1417 return CHECK_PERMISSION_FAILED;
1418 }
1419
1420 int32_t result = AuthEventListenerManager::GetInstance().UnRegistUserAuthSuccessEventListener(listener);
1421 if (result != SUCCESS) {
1422 IAM_LOGE("failed to unregist auth event listener");
1423 return result;
1424 }
1425
1426 return SUCCESS;
1427 }
1428
SetGlobalConfigParam(const GlobalConfigParam & param)1429 int32_t UserAuthService::SetGlobalConfigParam(const GlobalConfigParam ¶m)
1430 {
1431 IAM_LOGI("start, GlobalConfigType is %{public}d, userIds size %{public}zu, authTypes size %{public}zu",
1432 param.type, param.userIds.size(), param.authTypes.size());
1433 Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
1434 if (!IpcCommon::CheckPermission(*this, ACCESS_USER_AUTH_INTERNAL_PERMISSION) ||
1435 !IpcCommon::CheckPermission(*this, ENTERPRISE_DEVICE_MGR)) {
1436 IAM_LOGE("failed to check permission");
1437 return CHECK_PERMISSION_FAILED;
1438 }
1439 if (param.userIds.size() > MAX_USER || param.authTypes.size() > MAX_AUTH_TYPE_SIZE ||
1440 param.authTypes.size() == 0) {
1441 IAM_LOGE("bad global config param");
1442 return INVALID_PARAMETERS;
1443 }
1444
1445 HdiGlobalConfigParam paramConfig = {};
1446 switch (param.type) {
1447 case GlobalConfigType::PIN_EXPIRED_PERIOD:
1448 if (param.authTypes.size() != 1 || param.authTypes[0] != PIN) {
1449 IAM_LOGE("bad authTypes for PIN_EXPIRED_PERIOD");
1450 return INVALID_PARAMETERS;
1451 }
1452 paramConfig.value.pinExpiredPeriod = param.value.pinExpiredPeriod;
1453 break;
1454 case GlobalConfigType::ENABLE_STATUS:
1455 paramConfig.value.enableStatus = param.value.enableStatus;
1456 break;
1457 default:
1458 IAM_LOGE("bad global config type");
1459 return INVALID_PARAMETERS;
1460 }
1461 paramConfig.type = static_cast<HdiGlobalConfigType>(param.type);
1462 paramConfig.userIds = param.userIds;
1463 for (const auto authType : param.authTypes) {
1464 paramConfig.authTypes.push_back(authType);
1465 }
1466 auto hdi = HdiWrapper::GetHdiInstance();
1467 if (hdi == nullptr) {
1468 IAM_LOGE("hdi interface is nullptr");
1469 return GENERAL_ERROR;
1470 }
1471 int32_t result = hdi->SetGlobalConfigParam(paramConfig);
1472 if (result != SUCCESS) {
1473 IAM_LOGE("failed to Set global config param");
1474 return result;
1475 }
1476
1477 return SUCCESS;
1478 }
1479
CompleteRemoteAuthParam(RemoteAuthParam & remoteAuthParam,const std::string & localNetworkId)1480 bool UserAuthService::CompleteRemoteAuthParam(RemoteAuthParam &remoteAuthParam, const std::string &localNetworkId)
1481 {
1482 IAM_LOGI("start");
1483 if (remoteAuthParam.verifierNetworkId.has_value() && remoteAuthParam.verifierNetworkId->size() !=
1484 NETWORK_ID_LENGTH) {
1485 IAM_LOGE("invalid verifierNetworkId size");
1486 return false;
1487 }
1488
1489 if (remoteAuthParam.collectorNetworkId.has_value() && remoteAuthParam.collectorNetworkId->size() !=
1490 NETWORK_ID_LENGTH) {
1491 IAM_LOGE("invalid collectorNetworkId size");
1492 return false;
1493 }
1494
1495 if (!remoteAuthParam.verifierNetworkId.has_value() && !remoteAuthParam.collectorNetworkId.has_value()) {
1496 IAM_LOGE("neither verifierNetworkId nor collectorNetworkId is set");
1497 return false;
1498 } else if (remoteAuthParam.verifierNetworkId.has_value() && !remoteAuthParam.collectorNetworkId.has_value()) {
1499 IAM_LOGI("collectorNetworkId not set, verifierNetworkId set, use local networkId as collectorNetworkId");
1500 remoteAuthParam.collectorNetworkId = localNetworkId;
1501 } else if (!remoteAuthParam.verifierNetworkId.has_value() && remoteAuthParam.collectorNetworkId.has_value()) {
1502 IAM_LOGI("verifierNetworkId not set, collectorNetworkId set, use local networkId as verifierNetworkId");
1503 remoteAuthParam.verifierNetworkId = localNetworkId;
1504 }
1505
1506 if (remoteAuthParam.verifierNetworkId.value() != localNetworkId &&
1507 remoteAuthParam.collectorNetworkId.value() != localNetworkId) {
1508 IAM_LOGE("both verifierNetworkId and collectorNetworkId are not local networkId");
1509 return false;
1510 }
1511
1512 if (remoteAuthParam.verifierNetworkId.value() == remoteAuthParam.collectorNetworkId.value()) {
1513 IAM_LOGE("verifierNetworkId and collectorNetworkId are the same");
1514 return false;
1515 }
1516
1517 if (remoteAuthParam.verifierNetworkId == localNetworkId && !remoteAuthParam.collectorTokenId.has_value()) {
1518 IAM_LOGE("this device is verifier, collectorTokenId not set");
1519 return false;
1520 }
1521
1522 if (remoteAuthParam.collectorNetworkId == localNetworkId && !remoteAuthParam.collectorTokenId.has_value()) {
1523 IAM_LOGI("this device is collector, update collectorTokenId with caller token id");
1524 remoteAuthParam.collectorTokenId = IpcCommon::GetAccessTokenId(*this);
1525 }
1526
1527 IAM_LOGI("success");
1528 return true;
1529 }
1530
GetAuthTokenAttr(const HdiUserAuthTokenPlain & tokenPlain,const std::vector<uint8_t> & rootSecret,Attributes & extraInfo)1531 bool UserAuthService::GetAuthTokenAttr(const HdiUserAuthTokenPlain &tokenPlain, const std::vector<uint8_t> &rootSecret,
1532 Attributes &extraInfo)
1533 {
1534 bool setTokenVersionRet = extraInfo.SetUint32Value(Attributes::ATTR_TOKEN_VERSION, tokenPlain.version);
1535 IF_FALSE_LOGE_AND_RETURN_VAL(setTokenVersionRet == true, false);
1536 bool setUserIdRet = extraInfo.SetInt32Value(Attributes::ATTR_USER_ID, tokenPlain.userId);
1537 IF_FALSE_LOGE_AND_RETURN_VAL(setUserIdRet == true, false);
1538 bool setChallengeRet = extraInfo.SetUint8ArrayValue(Attributes::ATTR_CHALLENGE, tokenPlain.challenge);
1539 IF_FALSE_LOGE_AND_RETURN_VAL(setChallengeRet == true, false);
1540 bool setTimeStampRet = extraInfo.SetUint64Value(Attributes::ATTR_TOKEN_TIME_INTERVAL, tokenPlain.timeInterval);
1541 IF_FALSE_LOGE_AND_RETURN_VAL(setTimeStampRet == true, false);
1542 bool setTrustLevelRet = extraInfo.SetUint32Value(Attributes::ATTR_AUTH_TRUST_LEVEL, tokenPlain.authTrustLevel);
1543 IF_FALSE_LOGE_AND_RETURN_VAL(setTrustLevelRet == true, false);
1544 bool setAuthTypeRet = extraInfo.SetInt32Value(Attributes::ATTR_AUTH_TYPE, tokenPlain.authType);
1545 IF_FALSE_LOGE_AND_RETURN_VAL(setAuthTypeRet == true, false);
1546 bool setTokenTypeRet = extraInfo.SetInt32Value(Attributes::ATTR_TOKEN_TYPE, tokenPlain.tokenType);
1547 IF_FALSE_LOGE_AND_RETURN_VAL(setTokenTypeRet == true, false);
1548 bool setSecureUidRet = extraInfo.SetUint64Value(Attributes::ATTR_SEC_USER_ID, tokenPlain.secureUid);
1549 IF_FALSE_LOGE_AND_RETURN_VAL(setSecureUidRet == true, false);
1550 bool setEnrolledIdRet = extraInfo.SetUint64Value(Attributes::ATTR_CREDENTIAL_DIGEST, tokenPlain.enrolledId);
1551 IF_FALSE_LOGE_AND_RETURN_VAL(setEnrolledIdRet == true, false);
1552 bool setCredentialIdRet = extraInfo.SetUint64Value(Attributes::ATTR_CREDENTIAL_ID, tokenPlain.credentialId);
1553 IF_FALSE_LOGE_AND_RETURN_VAL(setCredentialIdRet == true, false);
1554 if (rootSecret.size() != 0) {
1555 bool setRootSecret = extraInfo.SetUint8ArrayValue(Attributes::ATTR_ROOT_SECRET, rootSecret);
1556 IF_FALSE_LOGE_AND_RETURN_VAL(setRootSecret == true, false);
1557 }
1558 return true;
1559 }
1560
VerifyAuthToken(const std::vector<uint8_t> & tokenIn,uint64_t allowableDuration,const sptr<VerifyTokenCallbackInterface> & callback)1561 void UserAuthService::VerifyAuthToken(const std::vector<uint8_t> &tokenIn, uint64_t allowableDuration,
1562 const sptr<VerifyTokenCallbackInterface> &callback)
1563 {
1564 IAM_LOGI("start, duration:%{public}" PRIu64 ", tokenIn size:%{public}zu.", allowableDuration, tokenIn.size());
1565 Common::XCollieHelper xcollie(__FUNCTION__, Common::API_CALL_TIMEOUT);
1566 IF_FALSE_LOGE_AND_RETURN(callback != nullptr);
1567
1568 Attributes extraInfo;
1569 if (tokenIn.size() == 0 || tokenIn.data() == nullptr || allowableDuration > MAX_TOKEN_ALLOWABLE_DURATION) {
1570 IAM_LOGE("bad parameter");
1571 callback->OnVerifyTokenResult(INVALID_PARAMETERS, extraInfo);
1572 return;
1573 }
1574 if (!IpcCommon::CheckPermission(*this, USE_USER_ACCESS_MANAGER)) {
1575 IAM_LOGE("failed to check permission");
1576 callback->OnVerifyTokenResult(CHECK_PERMISSION_FAILED, extraInfo);
1577 return;
1578 }
1579 if (IpcCommon::GetDirectCallerType(*this) != Security::AccessToken::TOKEN_NATIVE &&
1580 !IpcCommon::CheckPermission(*this, IS_SYSTEM_APP)) {
1581 IAM_LOGE("caller is not systemApp.");
1582 callback->OnVerifyTokenResult(CHECK_SYSTEM_APP_FAILED, extraInfo);
1583 return;
1584 }
1585
1586 auto hdi = HdiWrapper::GetHdiInstance();
1587 if (hdi == nullptr) {
1588 IAM_LOGE("hdi interface is nullptr");
1589 callback->OnVerifyTokenResult(GENERAL_ERROR, extraInfo);
1590 return;
1591 }
1592
1593 HdiUserAuthTokenPlain tokenPlain = {};
1594 std::vector<uint8_t> rootSecret = {};
1595 int32_t result = hdi->VerifyAuthToken(tokenIn, allowableDuration, tokenPlain, rootSecret);
1596 if (result != SUCCESS) {
1597 IAM_LOGE("VerifyAuthToken failed result:%{public}d", result);
1598 callback->OnVerifyTokenResult(result, extraInfo);
1599 return;
1600 }
1601 if (!GetAuthTokenAttr(tokenPlain, rootSecret, extraInfo)) {
1602 IAM_LOGE("GetAuthTokenAttr failed");
1603 callback->OnVerifyTokenResult(GENERAL_ERROR, extraInfo);
1604 return;
1605 }
1606 callback->OnVerifyTokenResult(SUCCESS, extraInfo);
1607 }
1608 } // namespace UserAuth
1609 } // namespace UserIam
1610 } // namespace OHOS