1 /*
2 * Copyright (c) 2025 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 <memory>
17
18 #include "app_manager.h"
19 #include "business_event.h"
20 #include "distributed_device_profile_client.h"
21 #include "softbus_common.h"
22 #include "system_ability_definition.h"
23 #include "iservice_registry.h"
24 #include "parameter.h"
25 #include "deviceprofile_connector.h"
26 #include "multiple_user_connector.h"
27
28 #include "auth_manager.h"
29 #include "dm_constants.h"
30 #include "dm_crypto.h"
31 #include "dm_random.h"
32 #include "dm_log.h"
33 #include "dm_timer.h"
34 #include "dm_radar_helper.h"
35 #include "dm_device_info.h"
36 #include "dm_anonymous.h"
37 #include "dm_auth_state_machine.h"
38 #include "dm_auth_context.h"
39 #include "dm_auth_message_processor.h"
40 #include "dm_auth_state.h"
41 #include "json_object.h"
42
43 #ifdef SUPPORT_MSDP
44 #include "spatial_awareness_mgr_client.h"
45 #endif
46
47 namespace OHOS {
48 namespace DistributedHardware {
49 namespace {
50
51 constexpr int32_t MIN_PIN_CODE = 100000;
52 constexpr int32_t MAX_PIN_CODE = 999999;
53 constexpr int32_t DM_ULTRASONIC_FORWARD = 0;
54 constexpr int32_t DM_ULTRASONIC_REVERSE = 1;
55 const char* IS_NEED_JOIN_LNN = "IsNeedJoinLnn";
56 constexpr const char* NEED_JOIN_LNN = "0";
57 constexpr const char* NO_NEED_JOIN_LNN = "1";
58 const char* DM_REJECT_KEY = "business_id_cast+_reject_event";
59 const char* DM_AUTH_DIALOG_REJECT = "is_auth_dialog_reject";
60 const char* DM_TIMESTAMP = "timestamp";
61
GetCloseSessionDelaySeconds(std::string & delaySecondsStr)62 int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr)
63 {
64 if (!IsNumberString(delaySecondsStr)) {
65 LOGE("Invalid parameter, param is not number.");
66 return 0;
67 }
68 const int32_t closeSessionDelaySecondsMax = 10;
69 int32_t delaySeconds = std::atoi(delaySecondsStr.c_str());
70 if (delaySeconds < 0 || delaySeconds > closeSessionDelaySecondsMax) {
71 LOGE("Invalid parameter, param out of range.");
72 return 0;
73 }
74 return delaySeconds;
75 }
76
GetBundleLabel(const std::string & bundleName)77 std::string GetBundleLabel(const std::string &bundleName)
78 {
79 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
80 if (samgr == nullptr) {
81 LOGE("Get ability manager failed");
82 return bundleName;
83 }
84
85 sptr<IRemoteObject> object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
86 if (object == nullptr) {
87 LOGE("object is NULL.");
88 return bundleName;
89 }
90
91 sptr<OHOS::AppExecFwk::IBundleMgr> bms = iface_cast<OHOS::AppExecFwk::IBundleMgr>(object);
92 if (bms == nullptr) {
93 LOGE("bundle manager service is NULL.");
94 return bundleName;
95 }
96
97 auto bundleResourceProxy = bms->GetBundleResourceProxy();
98 if (bundleResourceProxy == nullptr) {
99 LOGE("GetBundleResourceProxy fail");
100 return bundleName;
101 }
102 AppExecFwk::BundleResourceInfo resourceInfo;
103 auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName,
104 static_cast<uint32_t>(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo);
105 if (result != ERR_OK) {
106 LOGE("GetBundleResourceInfo failed");
107 return bundleName;
108 }
109 LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str());
110 return resourceInfo.label;
111 }
112
ParseExtraFromMap(const std::map<std::string,std::string> & bindParam)113 std::string ParseExtraFromMap(const std::map<std::string, std::string> &bindParam)
114 {
115 auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA);
116 if (iter != bindParam.end()) {
117 return iter->second;
118 }
119 return ConvertMapToJsonString(bindParam);
120 }
121
122 } // namespace
123
IsHmlSessionType(const std::string & sessionType)124 bool AuthManager::IsHmlSessionType(const std::string &sessionType)
125 {
126 return sessionType == CONN_SESSION_TYPE_HML;
127 }
128
AuthManager(std::shared_ptr<SoftbusConnector> softbusConnector,std::shared_ptr<HiChainConnector> hiChainConnector,std::shared_ptr<IDeviceManagerServiceListener> listener,std::shared_ptr<HiChainAuthConnector> hiChainAuthConnector)129 AuthManager::AuthManager(std::shared_ptr<SoftbusConnector> softbusConnector,
130 std::shared_ptr<HiChainConnector> hiChainConnector,
131 std::shared_ptr<IDeviceManagerServiceListener> listener,
132 std::shared_ptr<HiChainAuthConnector> hiChainAuthConnector)
133 {
134 LOGI("DmAuthManager constructor");
135 context_ = std::make_shared<DmAuthContext>();
136 context_->softbusConnector = softbusConnector;
137 context_->listener = listener;
138 context_->hiChainConnector = hiChainConnector;
139 context_->hiChainAuthConnector = hiChainAuthConnector;
140 context_->authUiStateMgr = std::make_shared<AuthUiStateManager>(context_->listener);
141 context_->authenticationMap[AUTH_TYPE_PIN] = nullptr;
142 context_->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr;
143 context_->authenticationMap[AUTH_TYPE_PIN_ULTRASONIC] = nullptr;
144 context_->authenticationMap[AUTH_TYPE_NFC] = nullptr;
145 context_->authenticationMap[AUTH_TYPE_CRE] = nullptr;
146 context_->accesser.dmVersion = DM_CURRENT_VERSION;
147 context_->accessee.dmVersion = DM_CURRENT_VERSION;
148 context_->timer = std::make_shared<DmTimer>();
149 context_->authMessageProcessor = std::make_shared<DmAuthMessageProcessor>();
150 context_->businessId = "";
151 }
152
~AuthManager()153 AuthManager::~AuthManager()
154 {
155 if (context_ != nullptr) {
156 context_->successFinished = true;
157 context_->authStateMachine->Stop(); // Stop statemMachine thread
158
159 if (context_->timer != nullptr) {
160 context_->timer->DeleteAll();
161 }
162 LOGI("AuthManager context variables destroy successful.");
163 }
164 {
165 std::lock_guard<std::mutex> lock(bindParamMutex_);
166 bindParam_.clear();
167 }
168 LOGI("DmAuthManager destructor");
169 }
170
RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback)171 void AuthManager::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback)
172 {
173 context_->cleanNotifyCallback = cleanNotifyCallback;
174 return;
175 }
176
SetAuthContext(std::shared_ptr<DmAuthContext> context)177 void AuthManager::SetAuthContext(std::shared_ptr<DmAuthContext> context)
178 {
179 this->context_ = context;
180 }
181
GetAuthContext()182 std::shared_ptr<DmAuthContext> AuthManager::GetAuthContext()
183 {
184 return this->context_;
185 }
186
GeneratePincode()187 std::string AuthManager::GeneratePincode()
188 {
189 LOGI("AuthManager::GeneratePincode start");
190 int32_t pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE);
191 context_->pinCode = std::to_string(pinCode);
192 return context_->pinCode;
193 }
194
RegisterUiStateCallback(const std::string pkgName)195 int32_t AuthManager::RegisterUiStateCallback(const std::string pkgName)
196 {
197 LOGI("AuthManager::RegisterUiStateCallback start");
198 if (context_->authUiStateMgr == nullptr) {
199 LOGE("AuthManager::RegisterUiStateCallback context_->authUiStateMgr is null.");
200 return ERR_DM_FAILED;
201 }
202 context_->authUiStateMgr->RegisterUiStateCallback(pkgName);
203 return DM_OK;
204 }
205
UnRegisterUiStateCallback(const std::string pkgName)206 int32_t AuthManager::UnRegisterUiStateCallback(const std::string pkgName)
207 {
208 LOGI("AuthManager::UnRegisterUiStateCallback start");
209 if (context_->authUiStateMgr == nullptr) {
210 LOGE("AuthManager::UnRegisterUiStateCallback context_->authUiStateMgr is null.");
211 return ERR_DM_FAILED;
212 }
213 context_->authUiStateMgr->UnRegisterUiStateCallback(pkgName);
214 return DM_OK;
215 }
216
UnAuthenticateDevice(const std::string & pkgName,const std::string & udid,int32_t bindLevel)217 int32_t AuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel)
218 {
219 LOGI("AuthManager::UnAuthenticateDevice start");
220 return ERR_DM_FAILED;
221 }
222
ImportAuthCode(const std::string & pkgName,const std::string & authCode)223 int32_t AuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode)
224 {
225 if (authCode.empty() || pkgName.empty()) {
226 LOGE("ImportAuthCode failed, authCode or pkgName is empty");
227 return ERR_DM_INPUT_PARA_INVALID;
228 }
229 context_->importAuthCode = authCode;
230 context_->importPkgName = pkgName;
231 context_->pinCode = authCode;
232 LOGI("AuthManager::ImportAuthCode ok");
233 return DM_OK;
234 }
235
UnBindDevice(const std::string & pkgName,const std::string & udid,int32_t bindLevel,const std::string & extra)236 int32_t AuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid,
237 int32_t bindLevel, const std::string &extra)
238 {
239 LOGI("AuthManager::UnBindDevice start");
240 return ERR_DM_FAILED;
241 }
242
StopAuthenticateDevice(const std::string & pkgName)243 int32_t AuthManager::StopAuthenticateDevice(const std::string &pkgName)
244 {
245 (void)pkgName;
246 LOGI("AuthManager::StopAuthenticateDevice start");
247
248 context_->reason = STOP_BIND;
249 if (context_->direction == DM_AUTH_SOURCE) {
250 context_->authStateMachine->TransitionTo(std::make_shared<AuthSrcFinishState>());
251 } else {
252 context_->authStateMachine->TransitionTo(std::make_shared<AuthSinkFinishState>());
253 }
254 return DM_OK;
255 }
256
OnScreenLocked()257 void AuthManager::OnScreenLocked()
258 {
259 LOGI("AuthManager::OnScreenLocked start");
260 if (DmAuthState::IsImportAuthCodeCompatibility(context_->authType)) {
261 LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", context_->authType);
262 return;
263 }
264 context_->reason = ERR_DM_BIND_USER_CANCEL;
265 context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL);
266 }
267
HandleDeviceNotTrust(const std::string & udid)268 void AuthManager::HandleDeviceNotTrust(const std::string &udid)
269 {
270 LOGI("AuthManager::HandleDeviceNotTrust start");
271 }
272
RegisterAuthenticationType(int32_t authenticationType)273 int32_t AuthManager::RegisterAuthenticationType(int32_t authenticationType)
274 {
275 context_->confirmOperation = static_cast<UiAction>(authenticationType);
276 return DM_OK;
277 }
278
GetReason()279 int32_t AuthManager::GetReason()
280 {
281 return context_->reason;
282 }
283
284 // Save the key
AuthDeviceSessionKey(int64_t requestId,const uint8_t * sessionKey,uint32_t sessionKeyLen)285 void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen)
286 {
287 LOGI("AuthSrcManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen);
288 if (context_ == nullptr || context_->authMessageProcessor == nullptr || context_->authStateMachine == nullptr) {
289 LOGE("AuthSrcManager::AuthDeviceSessionKey failed, auth context not initial.");
290 return;
291 }
292 if (requestId != context_->requestId) {
293 LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId);
294 return;
295 }
296 int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen);
297 if (ret != DM_OK) {
298 LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret);
299 }
300
301 context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED);
302 LOGI("AuthSrcManager::AuthDeviceSessionKey leave.");
303 }
304
AuthDeviceRequest(int64_t requestId,int operationCode,const char * reqParams)305 char *AuthSrcManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams)
306 {
307 LOGI("AuthSrcManager::AuthDeviceRequest start");
308 return nullptr;
309 }
310
SetAuthType(int32_t authType)311 void AuthManager::SetAuthType(int32_t authType)
312 {
313 context_->authType = (DmAuthType)authType;
314 }
315
IsAuthTypeSupported(const int32_t & authType)316 bool AuthManager::IsAuthTypeSupported(const int32_t &authType)
317 {
318 if (context_->authenticationMap.find(authType) == context_->authenticationMap.end()) {
319 LOGE("IsAuthTypeSupported failed, authType is not supported.");
320 return false;
321 }
322 return true;
323 }
324
IsAuthCodeReady(const std::string & pkgName)325 bool AuthManager::IsAuthCodeReady(const std::string &pkgName)
326 {
327 if (context_->importAuthCode.empty() || context_->importPkgName.empty()) {
328 LOGE("AuthManager::IsAuthCodeReady, auth code not ready with authCode %{public}s and pkgName %{public}s.",
329 GetAnonyString(context_->importAuthCode).c_str(), context_->importPkgName.c_str());
330 return false;
331 }
332 if (pkgName != context_->importPkgName) {
333 LOGE("AuthManager::IsAuthCodeReady pkgName %{public}s not supported with import pkgName %{public}s.",
334 pkgName.c_str(), context_->importPkgName.c_str());
335 return false;
336 }
337 return true;
338 }
339
CheckAuthParamVaild(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)340 int32_t AuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t authType,
341 const std::string &deviceId, const std::string &extra)
342 {
343 LOGI("AuthManager::CheckAuthParamVaild start.");
344 if (authType < DM_AUTH_TYPE_MIN || authType > DM_AUTH_TYPE_MAX) {
345 LOGE("CheckAuthParamVaild failed, authType is illegal.");
346 return ERR_DM_AUTH_FAILED;
347 }
348 if (pkgName.empty() || deviceId.empty()) {
349 LOGE("AuthManager::CheckAuthParamVaild failed, pkgName is %{public}s, deviceId is %{public}s, extra is"
350 "%{public}s.", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str());
351 return ERR_DM_INPUT_PARA_INVALID;
352 }
353 if (context_->listener == nullptr || context_->authUiStateMgr == nullptr) {
354 LOGE("AuthManager::CheckAuthParamVaild listener or authUiStateMgr is nullptr.");
355 return ERR_DM_INPUT_PARA_INVALID;
356 }
357
358 if (!IsAuthTypeSupported(authType)) {
359 LOGE("AuthManager::CheckAuthParamVaild authType %{public}d not support.", authType);
360 context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "",
361 STATUS_DM_AUTH_DEFAULT,
362 ERR_DM_UNSUPPORTED_AUTH_TYPE);
363 context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId,
364 ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, "");
365 return ERR_DM_UNSUPPORTED_AUTH_TYPE;
366 }
367 JsonObject jsonObject(extra);
368 if ((jsonObject.IsDiscarded() || !IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE) ||
369 jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get<std::string>() != CONN_SESSION_TYPE_HML) &&
370 !context_->softbusConnector->HaveDeviceInMap(deviceId)) {
371 LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device.");
372 context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "",
373 STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID);
374 context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId,
375 ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, "");
376 return ERR_DM_INPUT_PARA_INVALID;
377 }
378
379 if (DmAuthState::IsImportAuthCodeCompatibility(static_cast<DmAuthType>(authType)) &&
380 (!IsAuthCodeReady(pkgName))) {
381 LOGE("Auth code not exist.");
382 context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "",
383 STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID);
384 context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId,
385 ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, "");
386 return ERR_DM_INPUT_PARA_INVALID;
387 }
388 return DM_OK;
389 }
390
ParseHmlInfoInJsonObject(const JsonObject & jsonObject)391 void AuthManager::ParseHmlInfoInJsonObject(const JsonObject &jsonObject)
392 {
393 if (jsonObject[PARAM_KEY_CONN_SESSIONTYPE].IsString()) {
394 context_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get<std::string>();
395 LOGI("connSessionType %{public}s", context_->connSessionType.c_str());
396 }
397 if (!IsHmlSessionType(context_->connSessionType)) {
398 return;
399 }
400 if (context_->connDelayCloseTime == 0) {
401 context_->connDelayCloseTime = HML_SESSION_TIMEOUT;
402 }
403 if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBoolean()) {
404 context_->hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get<bool>();
405 LOGI("hmlEnable160M %{public}d", context_->hmlEnable160M);
406 }
407 if (jsonObject[PARAM_KEY_HML_ACTIONID].IsString()) {
408 std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get<std::string>();
409 if (IsNumberString(actionIdStr)) {
410 context_->hmlActionId = std::atoi(actionIdStr.c_str());
411 }
412 if (context_->hmlActionId <= 0) {
413 context_->hmlActionId = 0;
414 }
415 LOGI("hmlActionId %{public}d", context_->hmlActionId);
416 }
417
418 return;
419 }
420
GetBundleName(const JsonObject & jsonObject)421 std::string AuthManager::GetBundleName(const JsonObject &jsonObject)
422 {
423 if (!jsonObject.IsDiscarded() && jsonObject[BUNDLE_NAME_KEY].IsString()) {
424 return jsonObject[BUNDLE_NAME_KEY].Get<std::string>();
425 }
426 bool isSystemSA = false;
427 std::string bundleName;
428 AppManager::GetInstance().GetCallerName(isSystemSA, bundleName);
429 return bundleName;
430 }
431
ParseJsonObject(const JsonObject & jsonObject)432 void AuthManager::ParseJsonObject(const JsonObject &jsonObject)
433 {
434 if (IsString(jsonObject, DM_BUSINESS_ID)) {
435 context_->businessId = jsonObject[DM_BUSINESS_ID].Get<std::string>();
436 }
437 if (jsonObject[APP_OPERATION_KEY].IsString()) {
438 context_->appOperation = jsonObject[APP_OPERATION_KEY].Get<std::string>();
439 }
440 if (jsonObject[CUSTOM_DESCRIPTION_KEY].IsString()) {
441 context_->customData = jsonObject[CUSTOM_DESCRIPTION_KEY].Get<std::string>();
442 }
443 if (jsonObject[TAG_APP_THUMBNAIL2].IsString()) {
444 context_->appThumbnail = jsonObject[TAG_APP_THUMBNAIL2].Get<std::string>();
445 }
446 context_->connDelayCloseTime = 0;
447 if (jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].IsString()) {
448 std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].Get<std::string>();
449 context_->connDelayCloseTime = GetCloseSessionDelaySeconds(delaySecondsStr);
450 }
451
452 context_->accessee.bundleName = context_->accesser.bundleName;
453 if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString() && !jsonObject[TAG_PEER_BUNDLE_NAME].Get<std::string>().empty()) {
454 context_->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get<std::string>();
455 context_->accessee.oldBundleName = context_->accessee.bundleName;
456 } else {
457 context_->accessee.oldBundleName = context_->pkgName;
458 }
459
460 context_->accesser.pkgName = context_->pkgName;
461 context_->accessee.pkgName = context_->accesser.pkgName;
462
463 if (jsonObject[TAG_PEER_PKG_NAME].IsString()) {
464 context_->accessee.pkgName = jsonObject[TAG_PEER_PKG_NAME].Get<std::string>();
465 }
466
467 if (jsonObject[TAG_PEER_DISPLAY_ID].IsNumberInteger()) {
468 context_->accessee.displayId = jsonObject[TAG_PEER_DISPLAY_ID].Get<int32_t>();
469 }
470 if (jsonObject[TAG_LOCAL_USERID].IsNumberInteger()) {
471 context_->accesser.userId = jsonObject[TAG_LOCAL_USERID].Get<int32_t>();
472 } else {
473 context_->accesser.userId = MultipleUserConnector::GetFirstForegroundUserId();
474 }
475
476 if (context_->authType == AUTH_TYPE_PIN_ULTRASONIC) {
477 ParseUltrasonicSide(jsonObject);
478 }
479
480 ParseHmlInfoInJsonObject(jsonObject);
481 ParseProxyJsonObject(jsonObject);
482 return;
483 }
484
ParseUltrasonicSide(const JsonObject & jsonObject)485 void AuthManager::ParseUltrasonicSide(const JsonObject &jsonObject)
486 {
487 if (jsonObject[TAG_ULTRASONIC_SIDE].IsString()) {
488 std::string tempInfo = jsonObject[TAG_ULTRASONIC_SIDE].Get<std::string>();
489 if (tempInfo.length() > 0 && isdigit(tempInfo[0])) {
490 int32_t intTempInfo = std::atoi(tempInfo.c_str());
491 if (intTempInfo == DM_ULTRASONIC_REVERSE) {
492 context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Reverse;
493 } else if (intTempInfo == DM_ULTRASONIC_FORWARD) {
494 context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward;
495 } else {
496 context_->ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Invalid;
497 return;
498 }
499 }
500 }
501 bool isSupport = true;
502 if (context_->ultrasonicInfo == DM_Ultrasonic_Forward) {
503 #ifdef SUPPORT_MSDP
504 isSupport = Msdp::SpatialAwarenessMgrClient::GetInstance().IsPinCodeAbilitySupport(
505 Msdp::PinCodeMode::MODE_PIN_RECEIVE_CODE);
506 #endif
507 }
508 if (context_->ultrasonicInfo == DM_Ultrasonic_Reverse) {
509 #ifdef SUPPORT_MSDP
510 isSupport = Msdp::SpatialAwarenessMgrClient::GetInstance().IsPinCodeAbilitySupport(
511 Msdp::PinCodeMode::MODE_PIN_SEND_CODE);
512 #endif
513 }
514 if (!isSupport) {
515 context_->authType = AUTH_TYPE_PIN;
516 }
517 }
518
CheckBindLevel(const JsonItemObject & jsonObj,const std::string & key,int32_t & bindLevel)519 bool CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel)
520 {
521 if (IsJsonValIntegerString(jsonObj, TAG_BIND_LEVEL)) {
522 bindLevel = std::atoi(jsonObj[TAG_BIND_LEVEL].Get<std::string>().c_str());
523 return true;
524 }
525 if (IsInt32(jsonObj, TAG_BIND_LEVEL)) {
526 bindLevel = jsonObj[TAG_BIND_LEVEL].Get<int32_t>();
527 return true;
528 }
529 return false;
530 }
531
GetBindLevel(int32_t bindLevel)532 int32_t AuthManager::GetBindLevel(int32_t bindLevel)
533 {
534 LOGI("start.");
535 std::string processName = "";
536 bool isSystemSA = false;
537 {
538 std::lock_guard<std::mutex> lock(bindParamMutex_);
539 if (bindParam_.find("bindCallerProcessName") != bindParam_.end()) {
540 processName = bindParam_["bindCallerProcessName"];
541 }
542 if (bindParam_.find("bindCallerIsSystemSA") != bindParam_.end()) {
543 isSystemSA = static_cast<bool>(std::atoi(bindParam_["bindCallerIsSystemSA"].c_str()));
544 }
545 }
546 LOGI("processName = %{public}s, isSystemSA %{public}d.", GetAnonyString(processName).c_str(), isSystemSA);
547 if (processName != "" && AuthManagerBase::CheckProcessNameInWhiteList(processName)) {
548 return USER;
549 }
550 if (isSystemSA) {
551 if (static_cast<uint32_t>(bindLevel) == INVALIED_TYPE || static_cast<uint32_t>(bindLevel) > APP ||
552 static_cast<uint32_t>(bindLevel) < USER) {
553 return USER;
554 }
555 return bindLevel;
556 }
557 if (static_cast<uint32_t>(bindLevel) == INVALIED_TYPE || (static_cast<uint32_t>(bindLevel) != APP &&
558 static_cast<uint32_t>(bindLevel) != SERVICE)) {
559 return APP;
560 }
561 return bindLevel;
562 }
563
GetAuthParam(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)564 void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType,
565 const std::string &deviceId, const std::string &extra)
566 {
567 LOGI("Get auth param with pkgName %{public}s.", pkgName.c_str());
568 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
569 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
570 context_->accesser.deviceId = std::string(localDeviceId);
571 context_->pkgName = pkgName;
572 context_->authType = (DmAuthType)authType;
573 context_->accesser.deviceName = context_->listener->GetLocalDisplayDeviceName();
574 context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId();
575 context_->accesser.isOnline = false;
576
577 context_->accessee.deviceId = deviceId;
578 context_->accessee.addr = deviceId;
579 JsonObject jsonObject(extra);
580 if (jsonObject.IsDiscarded()) {
581 LOGE("extra string not a json type.");
582 return;
583 }
584 ParseJsonObject(jsonObject);
585 context_->accesser.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context_->accesser.userId);
586
587 // compatible for old version
588 context_->accesser.oldBindLevel = INVALIED_TYPE;
589 CheckBindLevel(jsonObject, TAG_BIND_LEVEL, context_->accesser.oldBindLevel);
590 context_->accesser.oldBindLevel = GetBindLevel(context_->accesser.oldBindLevel);
591 {
592 std::lock_guard<std::mutex> lock(bindParamMutex_);
593 bindParam_["bindCallerOldBindLevel"] = std::to_string(context_->accesser.oldBindLevel);
594 }
595 LOGI("bindCallerOldBindLevel %{public}d.", context_->accesser.oldBindLevel);
596 }
597
InitAuthState(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)598 void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType,
599 const std::string &deviceId, const std::string &extra)
600 {
601 auto iter = context_->authenticationMap.find(authType);
602 if (iter != context_->authenticationMap.end()) {
603 context_->authPtr = iter->second;
604 }
605
606 context_->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK),
607 AUTHENTICATE_TIMEOUT,
608 [this] (std::string name) {
609 DmAuthState::HandleAuthenticateTimeout(context_, name);
610 });
611 GetAuthParam(pkgName, authType, deviceId, extra);
612 context_->authStateMachine->TransitionTo(std::make_shared<AuthSrcStartState>());
613 LOGI("AuthManager::AuthenticateDevice complete");
614
615 return;
616 }
617
AuthenticateDevice(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)618 int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType,
619 const std::string &deviceId, const std::string &extra)
620 {
621 LOGI("AuthManager::AuthenticateDevice start auth type %{public}d.", authType);
622 SetAuthType(authType);
623 context_->processInfo.pkgName = pkgName;
624 GetBindCallerInfo();
625 int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra);
626 if (ret != DM_OK) {
627 LOGE("AuthManager::AuthenticateDevice failed, param is invaild.");
628 return ret;
629 }
630 ret = CheckProxyAuthParamVaild(extra);
631 if (ret != DM_OK) {
632 LOGE("CheckProxyAuthParamVaild failed.");
633 return ret;
634 }
635 context_->isAuthenticateDevice = true;
636 if (authType == AUTH_TYPE_CRE) {
637 LOGI("AuthManager::AuthenticateDevice for credential type, joinLNN directly.");
638 context_->softbusConnector->JoinLnn(deviceId, true);
639 context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId,
640 "", STATUS_DM_AUTH_DEFAULT, DM_OK);
641 context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId,
642 DM_OK, STATUS_DM_AUTH_DEFAULT, "");
643 return DM_OK;
644 }
645 InitAuthState(pkgName, authType, deviceId, extra);
646 if (context_->ultrasonicInfo == DmUltrasonicInfo::DM_Ultrasonic_Invalid) {
647 return ERR_DM_INPUT_PARA_INVALID;
648 }
649 return DM_OK;
650 }
651
BindTarget(const std::string & pkgName,const PeerTargetId & targetId,const std::map<std::string,std::string> & bindParam,int sessionId,uint64_t logicalSessionId)652 int32_t AuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId,
653 const std::map<std::string, std::string> &bindParam, int sessionId, uint64_t logicalSessionId)
654 {
655 int ret = DM_OK;
656 LOGI("AuthManager::BindTarget start. pkgName: %{public}s", pkgName.c_str());
657
658 struct RadarInfo info = {
659 .funcName = "AuthenticateDevice",
660 .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
661 .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
662 };
663 if (!DmRadarHelper::GetInstance().ReportDiscoverUserRes(info)) {
664 LOGE("ReportDiscoverUserRes failed");
665 }
666 GetIsNeedJoinLnnParam(bindParam);
667 if (pkgName.empty()) {
668 LOGE("AuthManager::BindTarget failed, pkgName is empty.");
669 return ERR_DM_INPUT_PARA_INVALID;
670 }
671 int32_t authType = -1;
672 if (ParseAuthType(bindParam, authType) != DM_OK) {
673 LOGE("AuthManager::BindTarget failed, key: %{public}s error.", PARAM_KEY_AUTH_TYPE);
674 return ERR_DM_INPUT_PARA_INVALID;
675 }
676 context_->peerTargetId = targetId_;
677 {
678 std::lock_guard<std::mutex> lock(bindParamMutex_);
679 bindParam_ = bindParam;
680 }
681 if (!targetId.deviceId.empty()) {
682 ret = AuthenticateDevice(pkgName, authType, targetId.deviceId, ParseExtraFromMap(bindParam));
683 if (ret != DM_OK) { return ret; }
684 } else {
685 LOGE("AuthManager::BindTarget failed, targetId is error.");
686 return ERR_DM_INPUT_PARA_INVALID;
687 }
688
689 context_->sessionId = sessionId;
690 context_->logicalSessionId = logicalSessionId;
691 context_->requestId = static_cast<int64_t>(logicalSessionId);
692 context_->authStateMachine->TransitionTo(std::make_shared<AuthSrcNegotiateStateMachine>());
693 info = { .funcName = "BindTarget" };
694 info.channelId = sessionId;
695 DmRadarHelper::GetInstance().ReportAuthSendRequest(info);
696 return ret;
697 }
698
GetIsNeedJoinLnnParam(const std::map<std::string,std::string> & bindParam)699 void AuthManager::GetIsNeedJoinLnnParam(const std::map<std::string, std::string> &bindParam)
700 {
701 std::string isNeedJoinLnnStr;
702 if (bindParam.find(IS_NEED_JOIN_LNN) != bindParam.end()) {
703 isNeedJoinLnnStr = bindParam.at(IS_NEED_JOIN_LNN);
704 }
705 if (isNeedJoinLnnStr == NEED_JOIN_LNN || isNeedJoinLnnStr == NO_NEED_JOIN_LNN) {
706 context_->isNeedJoinLnn = std::atoi(isNeedJoinLnnStr.c_str());
707 LOGI("isNeedJoinLnn: %{public}d.", context_->isNeedJoinLnn);
708 }
709 }
710
AuthSinkManager(std::shared_ptr<SoftbusConnector> softbusConnector,std::shared_ptr<HiChainConnector> hiChainConnector,std::shared_ptr<IDeviceManagerServiceListener> listener,std::shared_ptr<HiChainAuthConnector> hiChainAuthConnector)711 AuthSinkManager::AuthSinkManager(std::shared_ptr<SoftbusConnector> softbusConnector,
712 std::shared_ptr<HiChainConnector> hiChainConnector,
713 std::shared_ptr<IDeviceManagerServiceListener> listener,
714 std::shared_ptr<HiChainAuthConnector> hiChainAuthConnector)
715 : AuthManager(softbusConnector, hiChainConnector, listener, hiChainAuthConnector)
716 {
717 context_->direction = DM_AUTH_SINK;
718 context_->authStateMachine = std::make_shared<DmAuthStateMachine>(context_);
719 }
720
OnSessionOpened(int32_t sessionId,int32_t sessionSide,int32_t result)721 void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result)
722 {
723 LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result);
724 }
725
OnSessionClosed(int32_t sessionId)726 void AuthSinkManager::OnSessionClosed(int32_t sessionId)
727 {
728 LOGI("AuthSrcManager::OnSessionClosed sessionId = %{public}d", sessionId);
729 context_->reason = ERR_DM_SESSION_CLOSED;
730 context_->authStateMachine->TransitionTo(std::make_shared<AuthSinkFinishState>());
731 }
732
OnDataReceived(int32_t sessionId,std::string message)733 void AuthSinkManager::OnDataReceived(int32_t sessionId, std::string message)
734 {
735 context_->sessionId = sessionId;
736 int32_t ret = context_->authMessageProcessor->ParseMessage(context_, message);
737 if (ret != DM_OK) {
738 LOGE("OnDataReceived failed, parse input message error.");
739 context_->reason = ERR_DM_PARSE_MESSAGE_FAILED;
740 context_->authStateMachine->TransitionTo(std::make_shared<AuthSinkFinishState>());
741 }
742
743 return;
744 }
745
GetIsCryptoSupport()746 bool AuthSinkManager::GetIsCryptoSupport()
747 {
748 return false;
749 }
750
GetRemoteDeviceId(std::string & deviceId)751 void AuthManager::GetRemoteDeviceId(std::string &deviceId)
752 {
753 deviceId = (context_->direction == DM_AUTH_SOURCE) ? context_->accessee.deviceId : context_->accesser.deviceId;
754 return;
755 }
756
OnUserOperation(int32_t action,const std::string & params)757 int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ms)
758 {
759 LOGI("AuthSinkManager::OnUserOperation start.");
760 if (context_ == nullptr || context_->authStateMachine == nullptr) {
761 LOGE("OnUserOperation: Authenticate is not start");
762 return ERR_DM_AUTH_NOT_START;
763 }
764
765 std::string businessId = context_->businessId;
766 if (!businessId.empty()) {
767 LOGI("AuthSinkManager::OnUserOperation found businessId: %{public}s", businessId.c_str());
768 int32_t ret = HandleBusinessEvents(businessId, action);
769 if (ret != DM_OK) {
770 LOGE("AuthSinkManager::OnUserOperation failed to handle business events, ret: %{public}d", ret);
771 return ret;
772 }
773 }
774
775 switch (action) {
776 case USER_OPERATION_TYPE_CANCEL_AUTH:
777 case USER_OPERATION_TYPE_ALLOW_AUTH:
778 case USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS:
779 context_->confirmOperation = static_cast<UiAction>(action);
780 context_->reply = USER_OPERATION_TYPE_ALLOW_AUTH;
781 context_->userOperationParam = params;
782 if (action == USER_OPERATION_TYPE_CANCEL_AUTH) {
783 LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_AUTH.");
784 context_->reply = USER_OPERATION_TYPE_CANCEL_AUTH;
785 }
786 context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION);
787 break;
788 case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT:
789 LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT.");
790 context_->confirmOperation = USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT;
791 context_->reason = ERR_DM_PEER_CONFIRM_TIME_OUT;
792 context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL);
793 break;
794 case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY:
795 LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY.");
796 context_->confirmOperation = USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY;
797 context_->reason = ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY;
798 context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL);
799 break;
800 default:
801 LOGE("this action id not support");
802 break;
803 }
804 LOGI("AuthSinkManager::OnUserOperation leave.");
805 return DM_OK;
806 }
807
AuthSrcManager(std::shared_ptr<SoftbusConnector> softbusConnector,std::shared_ptr<HiChainConnector> hiChainConnector,std::shared_ptr<IDeviceManagerServiceListener> listener,std::shared_ptr<HiChainAuthConnector> hiChainAuthConnector)808 AuthSrcManager::AuthSrcManager(std::shared_ptr<SoftbusConnector> softbusConnector,
809 std::shared_ptr<HiChainConnector> hiChainConnector,
810 std::shared_ptr<IDeviceManagerServiceListener> listener,
811 std::shared_ptr<HiChainAuthConnector> hiChainAuthConnector)
812 : AuthManager(softbusConnector, hiChainConnector, listener, hiChainAuthConnector)
813 {
814 context_->direction = DM_AUTH_SOURCE;
815 context_->authStateMachine = std::make_shared<DmAuthStateMachine>(context_);
816 }
817
OnSessionOpened(int32_t sessionId,int32_t sessionSide,int32_t result)818 void AuthSrcManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result)
819 {
820 LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result);
821 }
822
OnSessionClosed(int32_t sessionId)823 void AuthSrcManager::OnSessionClosed(int32_t sessionId)
824 {
825 LOGI("AuthSrcManager::OnSessionClosed sessionId = %{public}d", sessionId);
826 context_->reason = ERR_DM_SESSION_CLOSED;
827 context_->authStateMachine->TransitionTo(std::make_shared<AuthSrcFinishState>());
828 }
829
OnSessionDisable()830 void AuthSrcManager::OnSessionDisable()
831 {
832 context_->sessionId = -1;
833 }
834
OnDataReceived(int32_t sessionId,std::string message)835 void AuthSrcManager::OnDataReceived(int32_t sessionId, std::string message)
836 {
837 context_->sessionId = sessionId;
838 int32_t ret = context_->authMessageProcessor->ParseMessage(context_, message);
839 if (ret != DM_OK) {
840 LOGE("OnDataReceived failed, parse input message error.");
841 context_->reason = ERR_DM_PARSE_MESSAGE_FAILED;
842 context_->authStateMachine->TransitionTo(std::make_shared<AuthSrcFinishState>());
843 }
844
845 return;
846 }
847
GetIsCryptoSupport()848 bool AuthSrcManager::GetIsCryptoSupport()
849 {
850 return false;
851 }
852
OnUserOperation(int32_t action,const std::string & params)853 int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶ms)
854 {
855 LOGI("AuthSrcManager::OnUserOperation start.");
856 if (context_ == nullptr || context_->authStateMachine == nullptr) {
857 LOGE("OnUserOperation: Authenticate is not start");
858 return ERR_DM_AUTH_NOT_START;
859 }
860
861 switch (action) {
862 case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT:
863 LOGE("AuthSrcManager OnUserOperation user cancel");
864 context_->pinInputResult = USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT;
865 context_->reason = ERR_DM_BIND_USER_CANCEL_ERROR;
866 context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL);
867 break;
868 case USER_OPERATION_TYPE_DONE_PINCODE_INPUT:
869 LOGE("AuthSrcManager OnUserOperation user input done");
870 context_->pinInputResult = USER_OPERATION_TYPE_DONE_PINCODE_INPUT;
871 {
872 if (!IsNumberString(params)) {
873 LOGE("OnUserOperation jsonStr error");
874 return ERR_DM_INPUT_PARA_INVALID;
875 }
876 context_->pinCode = params;
877 }
878 context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION);
879 break;
880 default:
881 LOGE("this action id not support");
882 break;
883 }
884 LOGI("AuthSrcManager::OnUserOperation leave.");
885 return DM_OK;
886 }
887
AuthDeviceError(int64_t requestId,int32_t errorCode)888 void AuthSrcManager::AuthDeviceError(int64_t requestId, int32_t errorCode)
889 {
890 LOGI("AuthSrcManager::AuthDeviceError start.");
891 CHECK_NULL_VOID(context_);
892 if (requestId != context_->requestId) {
893 LOGE("requestId: %{public}" PRId64", context_->requestId: %{public}" PRId64".", requestId, context_->requestId);
894 return;
895 }
896 auto curState = context_->authStateMachine->GetCurState();
897 if (curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE ||
898 curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE ||
899 curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE) {
900 LOGI("AuthSrcManager::AuthDeviceError Auth pin err.");
901 if (context_->authType == DmAuthType::AUTH_TYPE_PIN) {
902 context_->inputPinAuthFailTimes++;
903 }
904 context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR);
905 context_->authStateMachine->TransitionTo(std::make_shared<AuthSrcPinNegotiateStartState>());
906 } else {
907 LOGI("AuthSrcManager::AuthDeviceError unexpected err.");
908 context_->reason = errorCode;
909 context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL);
910 }
911 LOGI("AuthSrcManager::AuthDeviceError leave.");
912 }
913
AuthDeviceError(int64_t requestId,int32_t errorCode)914 void AuthSinkManager::AuthDeviceError(int64_t requestId, int32_t errorCode)
915 {
916 LOGI("AuthSinkManager::AuthDeviceError start.");
917 auto curState = context_->authStateMachine->GetCurState();
918 if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE ||
919 curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE) {
920 LOGI("AuthSrcManager::AuthDeviceError Auth pin err.");
921 if (context_->authType == DmAuthType::AUTH_TYPE_PIN) {
922 context_->inputPinAuthFailTimes++;
923 }
924 context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR);
925 context_->authStateMachine->TransitionTo(std::make_shared<AuthSinkPinNegotiateStartState>());
926 } else {
927 LOGI("AuthSinkManager::AuthDeviceError unexpected err.");
928 context_->reason = errorCode;
929 context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL);
930 }
931 LOGI("AuthSinkManager::AuthDeviceError leave.");
932 }
933
AuthDeviceTransmit(int64_t requestId,const uint8_t * data,uint32_t dataLen)934 bool AuthSrcManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen)
935 {
936 LOGI("AuthSrcManager::AuthDeviceTransmit start.");
937 // check request id first
938 if (requestId != context_->requestId) {
939 LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64"is error.", requestId);
940 return false;
941 }
942
943 context_->transmitData = std::string(reinterpret_cast<const char *>(data), dataLen);
944 context_->authStateMachine->NotifyEventFinish(ON_TRANSMIT);
945 LOGI("AuthSrcManager::AuthDeviceTransmit leave.");
946 return true;
947 }
948
AuthDeviceTransmit(int64_t requestId,const uint8_t * data,uint32_t dataLen)949 bool AuthSinkManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen)
950 {
951 LOGI("AuthSinkManager::AuthDeviceTransmit start.");
952 // check request id first
953 if (requestId != context_->requestId) {
954 LOGE("AuthSinkManager::onTransmit requestId %{public}" PRId64"is error.", requestId);
955 return false;
956 }
957
958 context_->transmitData = std::string(reinterpret_cast<const char *>(data), dataLen);
959 context_->authStateMachine->NotifyEventFinish(ON_TRANSMIT);
960 LOGI("AuthSinkManager::AuthDeviceTransmit leave.");
961 return true;
962 }
963
AuthDeviceFinish(int64_t requestId)964 void AuthSrcManager::AuthDeviceFinish(int64_t requestId)
965 {
966 LOGI("AuthSrcManager::AuthDeviceFinish start.");
967 context_->authStateMachine->NotifyEventFinish(ON_FINISH);
968 // Perform business processing based on the current state
969 DmAuthStateType curState = context_->authStateMachine->GetCurState();
970 switch (curState) {
971 case DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE:
972 // ON_FINISH event occurs, start credential exchange
973 context_->authStateMachine->TransitionTo(std::make_shared<AuthSrcCredentialExchangeState>());
974 break;
975 default:
976 break;
977 }
978 LOGI("AuthSrcManager::AuthDeviceFinish leave.");
979 }
980
AuthDeviceFinish(int64_t requestId)981 void AuthSinkManager::AuthDeviceFinish(int64_t requestId)
982 {
983 LOGI("AuthSinkManager::AuthDeviceFinish start.");
984 context_->authStateMachine->NotifyEventFinish(ON_FINISH);
985 LOGI("AuthSinkManager::AuthDeviceFinish leave.");
986 }
987
AuthDeviceSessionKey(int64_t requestId,const uint8_t * sessionKey,uint32_t sessionKeyLen)988 void AuthSinkManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen)
989 {
990 LOGI("AuthSrcManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen);
991 if (context_ == nullptr || context_->authMessageProcessor == nullptr || context_->authStateMachine == nullptr) {
992 LOGE("AuthSrcManager::AuthDeviceSessionKey failed, auth context not initial.");
993 return;
994 }
995 if (requestId != context_->requestId) {
996 LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId);
997 return;
998 }
999 int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen);
1000 if (ret != DM_OK) {
1001 LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret);
1002 }
1003
1004 context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED);
1005 }
1006
AuthDeviceRequest(int64_t requestId,int operationCode,const char * reqParams)1007 char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams)
1008 {
1009 LOGI("AuthSinkManager::AuthDeviceRequest start");
1010 (void)requestId;
1011 (void)reqParams;
1012 JsonObject jsonObj;
1013
1014 DmAuthStateType curState = context_->authStateMachine->GetCurState();
1015 if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE ||
1016 curState == DmAuthStateType::AUTH_SINK_REVERSE_ULTRASONIC_DONE_STATE||
1017 curState == DmAuthStateType::AUTH_SINK_FORWARD_ULTRASONIC_DONE_STATE) {
1018 std::string pinCode = "";
1019 if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == "") {
1020 jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED;
1021 } else {
1022 jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED;
1023 jsonObj[FIELD_PIN_CODE] = pinCode;
1024 }
1025 std::string pinCodeHash = GetAnonyString(Crypto::Sha256(pinCode));
1026 LOGI("AuthDeviceRequest pinCodeHash: %{public}s", pinCodeHash.c_str());
1027 } else if (curState == DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE) {
1028 if (context_->isOnline) { // Non-first time certification
1029 jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED;
1030 jsonObj[FIELD_CRED_ID] = context_->accessee.transmitCredentialId;
1031 } else if (!context_->isAppCredentialVerified) { // First-time authentication && appCred auth
1032 jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED;
1033 jsonObj[FIELD_CRED_ID] = context_->accessee.transmitCredentialId;
1034 } else { // First-time authentication && User credential authentication
1035 jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED;
1036 jsonObj[FIELD_CRED_ID] = context_->accessee.lnnCredentialId;
1037 }
1038 }
1039 jsonObj[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME);
1040 std::string jsonStr = jsonObj.Dump();
1041 char *buffer = strdup(jsonStr.c_str());
1042 return buffer;
1043 }
1044
GetPinCode(std::string & code)1045 int32_t AuthManager::GetPinCode(std::string &code)
1046 {
1047 if (context_ == nullptr) {
1048 LOGE("AuthManager failed to GetPinCode because context_ is nullptr");
1049 return ERR_DM_FAILED;
1050 }
1051 std::string pinCodeHash = GetAnonyString(Crypto::Sha256(context_->pinCode));
1052 LOGI("GetPinCode pinCodeHash: %{public}s", pinCodeHash.c_str());
1053 code = context_->pinCode;
1054 return DM_OK;
1055 }
1056
1057 // Reacquire BindParams to rebuild the link, generally used when switching between old and new protocol objects
GetBindTargetParams(std::string & pkgName,PeerTargetId & targetId,std::map<std::string,std::string> & bindParam)1058 void AuthManager::GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId,
1059 std::map<std::string, std::string> &bindParam)
1060 {
1061 pkgName = context_->pkgName;
1062 targetId = targetId_;
1063 {
1064 std::lock_guard<std::mutex> lock(bindParamMutex_);
1065 bindParam = bindParam_;
1066 }
1067 LOGI("AuthManager::GetBindTargetParams get pkgName %{public}s to reuse", pkgName.c_str());
1068 return;
1069 }
1070
GetAuthCodeAndPkgName(std::string & pkgName,std::string & authCode)1071 void AuthManager::GetAuthCodeAndPkgName(std::string &pkgName, std::string &authCode)
1072 {
1073 if (context_ == nullptr || context_->importAuthCode.empty() || context_->importPkgName.empty()) {
1074 LOGE("GetAuthCodeAndPkgName failed, authCode or pkgName is empty");
1075 return;
1076 }
1077 authCode = context_->importAuthCode;
1078 pkgName = context_->importPkgName;
1079 }
1080
SetBindTargetParams(const PeerTargetId & targetId)1081 void AuthManager::SetBindTargetParams(const PeerTargetId &targetId)
1082 {
1083 targetId_ = targetId;
1084 LOGI("AuthManager::SetBindTargetParams set targetId to reuse");
1085 return;
1086 }
1087
ClearSoftbusSessionCallback()1088 void AuthManager::ClearSoftbusSessionCallback()
1089 {}
1090
PrepareSoftbusSessionCallback()1091 void AuthManager::PrepareSoftbusSessionCallback()
1092 {}
1093
GetBindCallerInfo()1094 void AuthManager::GetBindCallerInfo()
1095 {
1096 LOGI("start.");
1097 {
1098 std::lock_guard<std::mutex> lock(bindParamMutex_);
1099 if (bindParam_.find("bindCallerUserId") != bindParam_.end()) {
1100 context_->processInfo.userId = std::atoi(bindParam_["bindCallerUserId"].c_str());
1101 }
1102 if (bindParam_.find("bindCallerTokenId") != bindParam_.end()) {
1103 context_->accesser.tokenId = std::atoi(bindParam_["bindCallerTokenId"].c_str());
1104 }
1105 if (bindParam_.find("bindCallerBindLevel") != bindParam_.end()) {
1106 context_->accesser.bindLevel = std::atoi(bindParam_["bindCallerBindLevel"].c_str());
1107 }
1108 if (bindParam_.find("bindCallerBundleName") != bindParam_.end()) {
1109 context_->accesser.bundleName = bindParam_["bindCallerBundleName"];
1110 }
1111 if (bindParam_.find("bindCallerHostPkgLabel") != bindParam_.end()) {
1112 context_->pkgLabel = bindParam_["bindCallerHostPkgLabel"];
1113 }
1114 }
1115 }
1116
DeleteTimer()1117 void AuthManager::DeleteTimer()
1118 {
1119 if (context_ != nullptr) {
1120 context_->successFinished = true;
1121 context_->authStateMachine->Stop(); // Stop statemMachine thread
1122 context_->timer->DeleteAll();
1123 LOGI("AuthManager context deleteTimer successful.");
1124 }
1125 {
1126 std::lock_guard<std::mutex> lock(bindParamMutex_);
1127 bindParam_.clear();
1128 }
1129 LOGI("end.");
1130 }
1131
HandleBusinessEvents(const std::string & businessId,int32_t action)1132 int32_t AuthManager::HandleBusinessEvents(const std::string &businessId, int32_t action)
1133 {
1134 LOGI("AuthManager::HandleBusinessEvents start.");
1135 DistributedDeviceProfile::BusinessEvent rejectEvent;
1136 rejectEvent.SetBusinessKey(DM_REJECT_KEY);
1137 JsonObject rejectJson;
1138 rejectJson[DM_BUSINESS_ID] = businessId;
1139 rejectJson[DM_AUTH_DIALOG_REJECT] = (action == USER_OPERATION_TYPE_CANCEL_AUTH);
1140 rejectJson[DM_TIMESTAMP] = std::to_string(GetCurrentTimestamp());
1141 rejectEvent.SetBusinessValue(rejectJson.Dump());
1142 int32_t ret = DistributedDeviceProfile::DistributedDeviceProfileClient::GetInstance().PutBusinessEvent(rejectEvent);
1143 if (ret != DM_OK) {
1144 LOGE("HandleBusinessEvents failed to store reject_event, ret: %{public}d", ret);
1145 return ret;
1146 }
1147 LOGI("HandleBusinessEvents successfully stored reject_event.");
1148 return DM_OK;
1149 }
CheckProxyAuthParamVaild(const std::string & extra)1150 int32_t AuthManager::CheckProxyAuthParamVaild(const std::string &extra)
1151 {
1152 LOGI("start.");
1153 JsonObject jsonObject(extra);
1154 if (jsonObject.IsDiscarded() || !IsString(jsonObject, PARAM_KEY_IS_PROXY_BIND)) {
1155 return DM_OK;
1156 }
1157 if (jsonObject[PARAM_KEY_IS_PROXY_BIND].Get<std::string>() != DM_VAL_TRUE) {
1158 return DM_OK;
1159 }
1160 if (!AppManager::GetInstance().IsSystemSA()) {
1161 LOGE("no proxy permission");
1162 return ERR_DM_NO_PERMISSION;
1163 }
1164 if (!jsonObject.Contains(PARAM_KEY_SUBJECT_PROXYED_SUBJECTS) ||
1165 !IsString(jsonObject, PARAM_KEY_SUBJECT_PROXYED_SUBJECTS)) {
1166 LOGE("no subject proxyed apps");
1167 return ERR_DM_INPUT_PARA_INVALID;
1168 }
1169 std::string subjectProxyOnesStr = jsonObject[PARAM_KEY_SUBJECT_PROXYED_SUBJECTS].Get<std::string>();
1170 JsonObject allProxyObj;
1171 allProxyObj.Parse(subjectProxyOnesStr);
1172 for (auto const &item : allProxyObj.Items()) {
1173 if (!item.Contains(TAG_BUNDLE_NAME) || !IsString(item, TAG_BUNDLE_NAME)) {
1174 LOGE("bundleName invalid");
1175 return ERR_DM_INPUT_PARA_INVALID;
1176 }
1177 if (!item.Contains(TAG_TOKENID) || !IsInt64(item, TAG_TOKENID)) {
1178 LOGE("tokenId invalid");
1179 return ERR_DM_INPUT_PARA_INVALID;
1180 }
1181 }
1182 return DM_OK;
1183 }
1184
ParseProxyJsonObject(const JsonObject & jsonObject)1185 void AuthManager::ParseProxyJsonObject(const JsonObject &jsonObject)
1186 {
1187 if (context_ == nullptr || jsonObject.IsDiscarded() || !IsString(jsonObject, PARAM_KEY_IS_PROXY_BIND) ||
1188 jsonObject[PARAM_KEY_IS_PROXY_BIND].Get<std::string>() != DM_VAL_TRUE) {
1189 return;
1190 }
1191 context_->IsProxyBind = true;
1192 if (IsString(jsonObject, PARAM_KEY_IS_CALLING_PROXY_AS_SUBJECT) &&
1193 jsonObject[PARAM_KEY_IS_CALLING_PROXY_AS_SUBJECT].Get<std::string>() == DM_VAL_FALSE) {
1194 context_->IsCallingProxyAsSubject = false;
1195 }
1196 if (!IsString(jsonObject, PARAM_KEY_SUBJECT_PROXYED_SUBJECTS)) {
1197 LOGE("no subject proxyed apps");
1198 return;
1199 }
1200 std::string subjectProxyOnesStr = jsonObject[PARAM_KEY_SUBJECT_PROXYED_SUBJECTS].Get<std::string>();
1201 JsonObject allProxyObj;
1202 allProxyObj.Parse(subjectProxyOnesStr);
1203 for (auto const &item : allProxyObj.Items()) {
1204 if (!IsString(item, TAG_BUNDLE_NAME)) {
1205 LOGE("bundleName invalid");
1206 return;
1207 }
1208 if (!IsInt64(item, TAG_TOKENID)) {
1209 LOGE("tokenId invalid");
1210 return;
1211 }
1212 std::string bundleName = item[TAG_BUNDLE_NAME].Get<std::string>();
1213 if (context_->accesser.bundleName == bundleName) {
1214 LOGE("proxy bundleName same as caller bundleName");
1215 return;
1216 }
1217 std::string peerBundleName = bundleName;
1218 if (item.Contains(PARAM_KEY_PEER_BUNDLE_NAME) && IsString(item, PARAM_KEY_PEER_BUNDLE_NAME)) {
1219 peerBundleName = item[PARAM_KEY_PEER_BUNDLE_NAME].Get<std::string>();
1220 }
1221 DmProxyAuthContext proxyAuthContext;
1222 proxyAuthContext.proxyContextId = Crypto::Sha256(bundleName + peerBundleName);
1223 if (std::find(context_->subjectProxyOnes.begin(), context_->subjectProxyOnes.end(), proxyAuthContext) ==
1224 context_->subjectProxyOnes.end()) {
1225 proxyAuthContext.proxyAccesser.bundleName = bundleName;
1226 proxyAuthContext.proxyAccesser.tokenId = item[TAG_TOKENID].Get<int64_t>();
1227 proxyAuthContext.proxyAccesser.tokenIdHash =
1228 Crypto::GetTokenIdHash(std::to_string(proxyAuthContext.proxyAccesser.tokenId));
1229 proxyAuthContext.proxyAccessee.bundleName = peerBundleName;
1230 GetBindLevelByBundleName(bundleName, context_->accesser.userId, proxyAuthContext.proxyAccesser.bindLevel);
1231 context_->subjectProxyOnes.push_back(proxyAuthContext);
1232 }
1233 }
1234 }
1235
GetBindLevelByBundleName(std::string & bundleName,int32_t userId,int32_t & bindLevel)1236 void AuthManager::GetBindLevelByBundleName(std::string &bundleName, int32_t userId, int32_t &bindLevel)
1237 {
1238 int64_t tokenId = 0;
1239 if (AppManager::GetInstance().GetHapTokenIdByName(userId, bundleName, 0, tokenId) == DM_OK) {
1240 bindLevel = DmRole::DM_ROLE_FA;
1241 } else if (AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tokenId) == DM_OK) {
1242 bindLevel = DmRole::DM_ROLE_SA;
1243 } else {
1244 LOGE("src not contain the bundlename %{public}s.", bundleName.c_str());
1245 }
1246 }
1247 } // namespace DistributedHardware
1248 } // namespace OHOS