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 "dm_auth_manager.h"
17
18 #include <algorithm>
19 #include <mutex>
20 #include <string>
21 #include <unistd.h>
22
23 #include "bundle_mgr_interface.h"
24 #include "bundle_mgr_proxy.h"
25 #include "iservice_registry.h"
26 #if defined(SUPPORT_SCREENLOCK)
27 #include "screenlock_manager.h"
28 #endif
29 #include "system_ability_definition.h"
30
31 #include "app_manager.h"
32 #include "auth_message_processor.h"
33 #include "common_event_support.h"
34 #include "dm_ability_manager.h"
35 #include "dm_anonymous.h"
36 #include "dm_config_manager.h"
37 #include "dm_constants.h"
38 #include "dm_crypto.h"
39 #include "dm_dialog_manager.h"
40 #include "dm_language_manager.h"
41 #include "dm_log.h"
42 #include "dm_radar_helper.h"
43 #include "dm_random.h"
44 #include "multiple_user_connector.h"
45 #include "json_object.h"
46 #include "openssl/sha.h"
47 #include "parameter.h"
48 #include "show_confirm.h"
49 #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE))
50 #include "multiple_user_connector.h"
51 #endif
52
53 namespace OHOS {
54 namespace DistributedHardware {
55 const int32_t AUTHENTICATE_TIMEOUT = 120;
56 const int32_t CONFIRM_TIMEOUT = 60;
57 const int32_t NEGOTIATE_TIMEOUT = 10;
58 const int32_t INPUT_TIMEOUT = 60;
59 const int32_t ADD_TIMEOUT = 10;
60 const int32_t WAIT_NEGOTIATE_TIMEOUT = 10;
61 const int32_t WAIT_REQUEST_TIMEOUT = 10;
62 const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20;
63 const int32_t CLONE_CONFIRM_TIMEOUT = 10;
64 const int32_t CLONE_NEGOTIATE_TIMEOUT = 10;
65 const int32_t CLONE_ADD_TIMEOUT = 10;
66 const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10;
67 const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10;
68 const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20;
69 const int32_t HML_SESSION_TIMEOUT = 10;
70 const int32_t CANCEL_PIN_CODE_DISPLAY = 1;
71 const int32_t DEVICE_ID_HALF = 2;
72 const int32_t MAX_AUTH_TIMES = 3;
73 const int32_t MIN_PIN_TOKEN = 10000000;
74 const int32_t MAX_PIN_TOKEN = 90000000;
75 const int32_t MIN_PIN_CODE = 100000;
76 const int32_t MAX_PIN_CODE = 999999;
77 const int32_t DM_AUTH_TYPE_MAX = 5;
78 const int32_t DM_AUTH_TYPE_MIN = 0;
79 const int32_t AUTH_SESSION_SIDE_SERVER = 0;
80 const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms
81 const int32_t AUTH_DEVICE_TIMEOUT = 10;
82 const int32_t SESSION_HEARTBEAT_TIMEOUT = 50;
83 const int32_t ALREADY_BIND = 1;
84 const int32_t STRTOLL_BASE_10 = 10;
85 const int32_t MAX_PUT_SESSIONKEY_TIMEOUT = 100; //ms
86 const int32_t SESSION_CLOSE_TIMEOUT = 5;
87
88 constexpr const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authenticate";
89 constexpr const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate";
90 constexpr const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm";
91 constexpr const char* INPUT_TIMEOUT_TASK = "deviceManagerTimer:input";
92 constexpr const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add";
93 constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate";
94 constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest";
95 constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_";
96 constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat";
97 constexpr const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK = "deviceManagerTimer:waitSessionClose";
98 constexpr const char* CLOSE_SESSION_TASK_SEPARATOR = "#";
99
100 constexpr int32_t PROCESS_NAME_WHITE_LIST_NUM = 1;
101 constexpr const static char* PROCESS_NAME_WHITE_LIST[PROCESS_NAME_WHITE_LIST_NUM] = {
102 "com.example.myapplication",
103 };
104
105 // clone task timeout map
106 const std::map<std::string, int32_t> TASK_TIME_OUT_MAP = {
107 { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT },
108 { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT },
109 { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT },
110 { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT },
111 { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT },
112 { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT },
113 { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT }
114 };
115
116 constexpr const char* APP_OPERATION_KEY = "appOperation";
117 constexpr const char* TARGET_PKG_NAME_KEY = "targetPkgName";
118 constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription";
119 constexpr const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay";
120 constexpr const char* BUNDLE_NAME_KEY = "bundleName";
121 constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1";
122 constexpr const char* DM_VERSION_5_0_1 = "5.0.1";
123 constexpr const char* DM_VERSION_5_0_2 = "5.0.2";
124 constexpr const char* DM_VERSION_5_0_3 = "5.0.3";
125 constexpr const char* DM_VERSION_5_0_4 = "5.0.4";
126 constexpr const char* DM_VERSION_5_0_5 = "5.0.5";
127 std::mutex g_authFinishLock;
128
DmAuthManager(std::shared_ptr<SoftbusConnector> softbusConnector,std::shared_ptr<HiChainConnector> hiChainConnector,std::shared_ptr<IDeviceManagerServiceListener> listener,std::shared_ptr<HiChainAuthConnector> hiChainAuthConnector)129 DmAuthManager::DmAuthManager(std::shared_ptr<SoftbusConnector> softbusConnector,
130 std::shared_ptr<HiChainConnector> hiChainConnector,
131 std::shared_ptr<IDeviceManagerServiceListener> listener,
132 std::shared_ptr<HiChainAuthConnector> hiChainAuthConnector)
133 : softbusConnector_(softbusConnector), hiChainConnector_(hiChainConnector), listener_(listener),
134 hiChainAuthConnector_(hiChainAuthConnector)
135 {
136 LOGI("DmAuthManager constructor");
137 DmConfigManager &dmConfigManager = DmConfigManager::GetInstance();
138 dmConfigManager.GetAuthAdapter(authenticationMap_);
139 authUiStateMgr_ = std::make_shared<AuthUiStateManager>(listener_);
140 authenticationMap_[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr;
141 authenticationMap_[AUTH_TYPE_CRE] = nullptr;
142 authenticationMap_[AUTH_TYPE_NFC] = nullptr;
143 dmVersion_ = DM_VERSION_5_0_5;
144 }
145
~DmAuthManager()146 DmAuthManager::~DmAuthManager()
147 {
148 LOGI("DmAuthManager destructor");
149 }
150
IsHmlSessionType()151 bool DmAuthManager::IsHmlSessionType()
152 {
153 CHECK_NULL_RETURN(authRequestContext_, false);
154 return authRequestContext_->connSessionType == CONN_SESSION_TYPE_HML;
155 }
156
CheckAuthParamVaild(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)157 int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t authType,
158 const std::string &deviceId, const std::string &extra)
159 {
160 LOGI("DmAuthManager::CheckAuthParamVaild start.");
161 if (authType < DM_AUTH_TYPE_MIN || authType > DM_AUTH_TYPE_MAX) {
162 LOGE("CheckAuthParamVaild failed, authType is illegal.");
163 return ERR_DM_AUTH_FAILED;
164 }
165 if (pkgName.empty() || deviceId.empty()) {
166 LOGE("DmAuthManager::CheckAuthParamVaild failed, pkgName is %{public}s, deviceId is %{public}s, extra is"
167 "%{public}s.", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str());
168 return ERR_DM_INPUT_PARA_INVALID;
169 }
170 if (listener_ == nullptr || authUiStateMgr_ == nullptr) {
171 LOGE("DmAuthManager::CheckAuthParamVaild listener or authUiStateMgr is nullptr.");
172 return ERR_DM_INPUT_PARA_INVALID;
173 }
174
175 if (!IsAuthTypeSupported(authType)) {
176 LOGE("DmAuthManager::CheckAuthParamVaild authType %{public}d not support.", authType);
177 listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT,
178 ERR_DM_UNSUPPORTED_AUTH_TYPE);
179 listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, "");
180 return ERR_DM_UNSUPPORTED_AUTH_TYPE;
181 }
182
183 if (authRequestState_ != nullptr || authResponseState_ != nullptr) {
184 LOGE("DmAuthManager::CheckAuthParamVaild %{public}s is request authentication.", pkgName.c_str());
185 return ERR_DM_AUTH_BUSINESS_BUSY;
186 }
187
188 if ((authType == AUTH_TYPE_IMPORT_AUTH_CODE || authType == AUTH_TYPE_NFC) && (!IsAuthCodeReady(pkgName))) {
189 LOGE("Auth code not exist.");
190 listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT,
191 ERR_DM_INPUT_PARA_INVALID);
192 listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, "");
193 return ERR_DM_INPUT_PARA_INVALID;
194 }
195 return DM_OK;
196 }
197
CheckAuthParamVaildExtra(const std::string & extra,const std::string & deviceId)198 int32_t DmAuthManager::CheckAuthParamVaildExtra(const std::string &extra, const std::string &deviceId)
199 {
200 JsonObject jsonObject(extra);
201 if ((jsonObject.IsDiscarded() || !IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE) ||
202 jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get<std::string>() != CONN_SESSION_TYPE_HML) &&
203 !softbusConnector_->HaveDeviceInMap(deviceId)) {
204 LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device.");
205 listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT,
206 ERR_DM_INPUT_PARA_INVALID);
207 listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, "");
208 return ERR_DM_INPUT_PARA_INVALID;
209 }
210 if (jsonObject.IsDiscarded()) {
211 return DM_OK;
212 }
213 std::string connSessionType;
214 if (IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE)) {
215 connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get<std::string>();
216 }
217 if (connSessionType == CONN_SESSION_TYPE_HML && !CheckHmlParamValid(jsonObject)) {
218 LOGE("CONN_SESSION_TYPE_HML, CheckHmlParamValid failed");
219 return ERR_DM_INPUT_PARA_INVALID;
220 }
221
222 if (jsonObject.IsDiscarded() || !jsonObject.Contains(TAG_BIND_LEVEL)) {
223 return DM_OK;
224 }
225 int32_t bindLevel = INVALID_TYPE;
226 if (!CheckBindLevel(jsonObject, TAG_BIND_LEVEL, bindLevel)) {
227 LOGE("TAG_BIND_LEVEL is not integer string or int32.");
228 return ERR_DM_INPUT_PARA_INVALID;
229 }
230 LOGI("bindlevel = %{public}d.", bindLevel);
231 if (static_cast<uint32_t>(bindLevel) > APP || bindLevel < INVALID_TYPE) {
232 LOGE("bindlevel error %{public}d.", bindLevel);
233 return ERR_DM_INPUT_PARA_INVALID;
234 }
235
236 if (static_cast<uint32_t>(bindLevel) == DEVICE && !IsAllowDeviceBind()) {
237 LOGE("not allowd device level bind bindlevel: %{public}d.", bindLevel);
238 return ERR_DM_INPUT_PARA_INVALID;
239 }
240 return DM_OK;
241 }
242
CheckBindLevel(const JsonItemObject & jsonObj,const std::string & key,int32_t & bindLevel)243 bool DmAuthManager::CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel)
244 {
245 if (IsJsonValIntegerString(jsonObj, TAG_BIND_LEVEL)) {
246 bindLevel = std::atoi(jsonObj[TAG_BIND_LEVEL].Get<std::string>().c_str());
247 return true;
248 }
249 if (IsInt32(jsonObj, TAG_BIND_LEVEL)) {
250 bindLevel = jsonObj[TAG_BIND_LEVEL].Get<int32_t>();
251 return true;
252 }
253 return false;
254 }
255
CheckHmlParamValid(JsonObject & jsonObject)256 bool DmAuthManager::CheckHmlParamValid(JsonObject &jsonObject)
257 {
258 if (!IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) {
259 LOGE("PARAM_KEY_HML_ACTIONID is not string");
260 return false;
261 }
262 std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get<std::string>();
263 if (!IsNumberString(actionIdStr)) {
264 LOGE("PARAM_KEY_HML_ACTIONID is not number");
265 return false;
266 }
267 int32_t actionId = std::atoi(actionIdStr.c_str());
268 if (actionId <= 0) {
269 LOGE("PARAM_KEY_HML_ACTIONID is <= 0");
270 return false;
271 }
272 return true;
273 }
274
CheckProcessNameInWhiteList(const std::string & processName)275 bool DmAuthManager::CheckProcessNameInWhiteList(const std::string &processName)
276 {
277 LOGI("DmAuthManager::CheckProcessNameInWhiteList start");
278 if (processName.empty()) {
279 LOGE("processName is empty");
280 return false;
281 }
282 uint16_t index = 0;
283 for (; index < PROCESS_NAME_WHITE_LIST_NUM; ++index) {
284 std::string whitePkgName(PROCESS_NAME_WHITE_LIST[index]);
285 if (processName == whitePkgName) {
286 LOGI("processName = %{public}s in whiteList.", processName.c_str());
287 return true;
288 }
289 }
290 LOGI("CheckProcessNameInWhiteList: %{public}s invalid.", processName.c_str());
291 return false;
292 }
293
GetAuthParam(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)294 void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType,
295 const std::string &deviceId, const std::string &extra)
296 {
297 LOGI("Get auth param.");
298 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
299 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
300 std::string localUdid = static_cast<std::string>(localDeviceId);
301 authRequestContext_->hostPkgName = pkgName;
302 authRequestContext_->hostPkgLabel = GetBundleLable(pkgName);
303 authRequestContext_->authType = authType;
304 authRequestContext_->localDeviceName = softbusConnector_->GetLocalDeviceName();
305 authRequestContext_->localDeviceTypeId = softbusConnector_->GetLocalDeviceTypeId();
306 authRequestContext_->localDeviceId = localUdid;
307 authRequestContext_->deviceId = deviceId;
308 authRequestContext_->addr = deviceId;
309 authRequestContext_->dmVersion = DM_VERSION_5_0_5;
310 uint32_t tokenId = 0 ;
311 MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, authRequestContext_->localUserId);
312 authRequestContext_->tokenId = static_cast<int64_t>(tokenId);
313 authRequestContext_->localAccountId =
314 MultipleUserConnector::GetOhosAccountIdByUserId(authRequestContext_->localUserId);
315 authRequestContext_->isOnline = false;
316 authRequestContext_->authed = !authRequestContext_->bindType.empty();
317 authRequestContext_->bindLevel = INVALIED_TYPE;
318 JsonObject jsonObject(extra);
319 if (jsonObject.IsDiscarded()) {
320 LOGE("extra string not a json type.");
321 return;
322 }
323 ParseJsonObject(jsonObject);
324 authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN));
325 authRequestContext_->bindLevel = GetBindLevel(authRequestContext_->bindLevel);
326 }
327
ParseJsonObject(JsonObject & jsonObject)328 void DmAuthManager::ParseJsonObject(JsonObject &jsonObject)
329 {
330 if (!jsonObject.IsDiscarded()) {
331 if (IsString(jsonObject, TARGET_PKG_NAME_KEY)) {
332 authRequestContext_->targetPkgName = jsonObject[TARGET_PKG_NAME_KEY].Get<std::string>();
333 }
334 if (IsString(jsonObject, APP_OPERATION_KEY)) {
335 authRequestContext_->appOperation = jsonObject[APP_OPERATION_KEY].Get<std::string>();
336 }
337 if (IsString(jsonObject, CUSTOM_DESCRIPTION_KEY)) {
338 authRequestContext_->customDesc = DmLanguageManager::GetInstance().
339 GetTextBySystemLanguage(jsonObject[CUSTOM_DESCRIPTION_KEY].Get<std::string>());
340 }
341 if (IsString(jsonObject, APP_THUMBNAIL)) {
342 authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL].Get<std::string>();
343 }
344 CheckBindLevel(jsonObject, TAG_BIND_LEVEL, authRequestContext_->bindLevel);
345 authRequestContext_->closeSessionDelaySeconds = 0;
346 if (IsString(jsonObject, PARAM_CLOSE_SESSION_DELAY_SECONDS)) {
347 std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].Get<std::string>();
348 authRequestContext_->closeSessionDelaySeconds = GetCloseSessionDelaySeconds(delaySecondsStr);
349 }
350 if (IsString(jsonObject, TAG_PEER_BUNDLE_NAME)) {
351 authRequestContext_->peerBundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get<std::string>();
352 if (authRequestContext_->peerBundleName == "") {
353 authRequestContext_->peerBundleName = authRequestContext_->hostPkgName;
354 }
355 LOGI("ParseJsonObject peerBundleName = %{public}s", authRequestContext_->peerBundleName.c_str());
356 } else {
357 authRequestContext_->peerBundleName = authRequestContext_->hostPkgName;
358 }
359 ParseHmlInfoInJsonObject(jsonObject);
360 }
361 authRequestContext_->bundleName = GetBundleName(jsonObject);
362 }
363
ParseHmlInfoInJsonObject(JsonObject & jsonObject)364 void DmAuthManager::ParseHmlInfoInJsonObject(JsonObject &jsonObject)
365 {
366 CHECK_NULL_VOID(authRequestContext_);
367 if (IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE)) {
368 authRequestContext_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get<std::string>();
369 LOGI("connSessionType %{public}s", authRequestContext_->connSessionType.c_str());
370 }
371 if (!IsHmlSessionType()) {
372 return;
373 }
374 if (IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) {
375 std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get<std::string>();
376 if (IsNumberString(actionIdStr)) {
377 authRequestContext_->hmlActionId = std::atoi(actionIdStr.c_str());
378 }
379 if (authRequestContext_->hmlActionId <= 0) {
380 authRequestContext_->hmlActionId = 0;
381 }
382 LOGI("hmlActionId %{public}d", authRequestContext_->hmlActionId);
383 }
384 }
385
GetCloseSessionDelaySeconds(std::string & delaySecondsStr)386 int32_t DmAuthManager::GetCloseSessionDelaySeconds(std::string &delaySecondsStr)
387 {
388 if (!IsNumberString(delaySecondsStr)) {
389 LOGE("Invalid parameter, param is not number.");
390 return 0;
391 }
392 const int32_t CLOSE_SESSION_DELAY_SECONDS_MAX = 10;
393 int32_t delaySeconds = std::atoi(delaySecondsStr.c_str());
394 if (delaySeconds < 0 || delaySeconds > CLOSE_SESSION_DELAY_SECONDS_MAX) {
395 LOGE("Invalid parameter, param out of range.");
396 return 0;
397 }
398 return delaySeconds;
399 }
400
InitAuthState(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)401 void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType,
402 const std::string &deviceId, const std::string &extra)
403 {
404 auto iter = authenticationMap_.find(authType);
405 if (iter != authenticationMap_.end()) {
406 authPtr_ = iter->second;
407 }
408
409 if (timer_ == nullptr) {
410 timer_ = std::make_shared<DmTimer>();
411 }
412 timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK),
413 GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) {
414 DmAuthManager::HandleAuthenticateTimeout(name);
415 });
416 authMessageProcessor_ = std::make_shared<AuthMessageProcessor>(shared_from_this());
417 authResponseContext_ = std::make_shared<DmAuthResponseContext>();
418 authRequestContext_ = std::make_shared<DmAuthRequestContext>();
419 GetAuthParam(pkgName, authType, deviceId, extra);
420 authMessageProcessor_->SetRequestContext(authRequestContext_);
421 authRequestState_ = std::make_shared<AuthRequestInitState>();
422 authRequestState_->SetAuthManager(shared_from_this());
423 authRequestState_->SetAuthContext(authRequestContext_);
424 if (!DmRadarHelper::GetInstance().ReportAuthStart(peerTargetId_.deviceId, pkgName)) {
425 LOGE("ReportAuthStart failed");
426 }
427 authRequestState_->Enter();
428 LOGI("DmAuthManager::AuthenticateDevice complete");
429 }
430
AuthenticateDevice(const std::string & pkgName,int32_t authType,const std::string & deviceId,const std::string & extra)431 int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType,
432 const std::string &deviceId, const std::string &extra)
433 {
434 LOGI("DmAuthManager::AuthenticateDevice start auth type %{public}d.", authType);
435 SetAuthType(authType);
436 int32_t userId = -1;
437 MultipleUserConnector::GetCallerUserId(userId);
438 processInfo_.pkgName = pkgName;
439 processInfo_.userId = userId;
440 int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra);
441 if (ret != DM_OK) {
442 LOGE("DmAuthManager::AuthenticateDevice failed, param is invaild.");
443 return ret;
444 }
445 ret = CheckAuthParamVaildExtra(extra, deviceId);
446 if (ret != DM_OK) {
447 LOGE("CheckAuthParamVaildExtra failed, param is invaild.");
448 return ret;
449 }
450 isAuthenticateDevice_ = true;
451 if (authType == AUTH_TYPE_CRE) {
452 LOGI("DmAuthManager::AuthenticateDevice for credential type, joinLNN directly.");
453 softbusConnector_->JoinLnn(deviceId, true);
454 listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, DM_OK);
455 listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_AUTH_DEFAULT, "");
456 return DM_OK;
457 }
458 InitAuthState(pkgName, authType, deviceId, extra);
459 return DM_OK;
460 }
461
UnAuthenticateDevice(const std::string & pkgName,const std::string & udid,int32_t bindLevel)462 int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel)
463 {
464 if (pkgName.empty()) {
465 LOGE("Invalid parameter, pkgName is empty.");
466 return ERR_DM_FAILED;
467 }
468 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
469 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
470 struct RadarInfo info = {
471 .funcName = "UnAuthenticateDevice",
472 .toCallPkg = HICHAINNAME,
473 .hostName = pkgName,
474 .peerUdid = udid,
475 };
476 if (!DmRadarHelper::GetInstance().ReportDeleteTrustRelation(info)) {
477 LOGE("ReportDeleteTrustRelation failed");
478 }
479 remoteDeviceId_ = udid;
480 if (bindLevel == DEVICE) {
481 DeleteGroup(pkgName, udid);
482 }
483 std::string extra = "";
484 return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra);
485 }
486
StopAuthenticateDevice(const std::string & pkgName)487 int32_t DmAuthManager::StopAuthenticateDevice(const std::string &pkgName)
488 {
489 if (pkgName.empty() || authRequestContext_ == nullptr || authResponseContext_ == nullptr) {
490 LOGE("Invalid parameter, pkgName is empty.");
491 return ERR_DM_INPUT_PARA_INVALID;
492 }
493 if (((authRequestState_!= nullptr && authRequestContext_->hostPkgName == pkgName) ||
494 (authResponseContext_ != nullptr && authResponseContext_->hostPkgName == pkgName)) &&
495 isAuthenticateDevice_) {
496 LOGI("Stop previous AuthenticateDevice.");
497 authRequestContext_->reason = STOP_BIND;
498 authResponseContext_->state = authRequestState_->GetStateType();
499 authResponseContext_->reply = STOP_BIND;
500 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
501 }
502 return DM_OK;
503 }
504
DeleteAcl(const std::string & pkgName,const std::string & localUdid,const std::string & remoteUdid,int32_t bindLevel,const std::string & extra)505 int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string &localUdid,
506 const std::string &remoteUdid, int32_t bindLevel, const std::string &extra)
507 {
508 LOGI("DeleteAcl pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.",
509 pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel);
510 DmOfflineParam offlineParam =
511 DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localUdid, remoteUdid, bindLevel, extra);
512 if (offlineParam.bindType == INVALIED_TYPE) {
513 LOGE("Acl not contain the pkgname bind data.");
514 return ERR_DM_FAILED;
515 }
516 if (bindLevel == APP) {
517 ProcessInfo processInfo;
518 processInfo.pkgName = pkgName;
519 processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId();
520 if (offlineParam.leftAclNumber != 0) {
521 LOGI("The pkgName unbind app-level type leftAclNumber not zero.");
522 softbusConnector_->SetProcessInfoVec(offlineParam.processVec);
523 softbusConnector_->HandleDeviceOffline(remoteUdid);
524 return DM_OK;
525 }
526 if (offlineParam.leftAclNumber == 0) {
527 LOGI("The pkgName unbind app-level type leftAclNumber is zero.");
528 softbusConnector_->SetProcessInfoVec(offlineParam.processVec);
529 hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID());
530 return DM_OK;
531 }
532 }
533 if (bindLevel == DEVICE && offlineParam.leftAclNumber != 0) {
534 LOGI("Unbind deivce-level, retain identical account bind type.");
535 return DM_OK;
536 }
537 if (bindLevel == DEVICE && offlineParam.leftAclNumber == 0) {
538 LOGI("Unbind deivce-level, retain null.");
539 hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID());
540 return DM_OK;
541 }
542 return ERR_DM_FAILED;
543 }
544
UnBindDevice(const std::string & pkgName,const std::string & udid,int32_t bindLevel,const std::string & extra)545 int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid,
546 int32_t bindLevel, const std::string &extra)
547 {
548 if (pkgName.empty()) {
549 LOGE("Invalid parameter, pkgName is empty.");
550 return ERR_DM_FAILED;
551 }
552 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
553 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
554 if (bindLevel == DEVICE) {
555 DeleteGroup(pkgName, udid);
556 }
557 return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra);
558 }
559
GetPeerUdidHash(int32_t sessionId,std::string & peerUdidHash)560 void DmAuthManager::GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash)
561 {
562 std::string peerUdid = "";
563 int32_t ret = softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid);
564 if (ret != DM_OK) {
565 LOGE("DmAuthManager::GetPeerUdidHash failed.");
566 peerUdidHash = "";
567 return;
568 }
569 char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0};
570 if (Crypto::GetUdidHash(peerUdid, reinterpret_cast<uint8_t *>(udidHashTmp)) != DM_OK) {
571 LOGE("get udidhash by udid: %{public}s failed.", GetAnonyString(peerUdid).c_str());
572 peerUdidHash = "";
573 return;
574 }
575 peerUdidHash = std::string(udidHashTmp);
576 }
577
DeleteOffLineTimer(int32_t sessionId)578 void DmAuthManager::DeleteOffLineTimer(int32_t sessionId)
579 {
580 GetPeerUdidHash(sessionId, remoteUdidHash_);
581 if (remoteUdidHash_.empty()) {
582 LOGE("DeleteOffLineTimer remoteUdidHash is empty.");
583 return;
584 }
585 if (softbusConnector_ != nullptr) {
586 softbusConnector_->DeleteOffLineTimer(remoteUdidHash_);
587 }
588 }
589
OnSessionOpened(int32_t sessionId,int32_t sessionSide,int32_t result)590 void DmAuthManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result)
591 {
592 LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result);
593 DeleteOffLineTimer(sessionId);
594 if (sessionSide == AUTH_SESSION_SIDE_SERVER) {
595 if (authResponseState_ == nullptr && authRequestState_ == nullptr) {
596 authMessageProcessor_ = std::make_shared<AuthMessageProcessor>(shared_from_this());
597 authResponseState_ = std::make_shared<AuthResponseInitState>();
598 authResponseState_->SetAuthManager(shared_from_this());
599 authResponseState_->Enter();
600 authResponseContext_ = std::make_shared<DmAuthResponseContext>();
601 authResponseContext_->sessionId = sessionId;
602 if (timer_ == nullptr) {
603 timer_ = std::make_shared<DmTimer>();
604 }
605 timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK),
606 GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) {
607 DmAuthManager::HandleAuthenticateTimeout(name);
608 });
609 timer_->StartTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK),
610 GetTaskTimeout(WAIT_NEGOTIATE_TIMEOUT_TASK, WAIT_NEGOTIATE_TIMEOUT), [this] (std::string name) {
611 DmAuthManager::HandleAuthenticateTimeout(name);
612 });
613 } else {
614 std::shared_ptr<AuthMessageProcessor> authMessageProcessor =
615 std::make_shared<AuthMessageProcessor>(shared_from_this());
616 std::shared_ptr<DmAuthResponseContext> authResponseContext = std::make_shared<DmAuthResponseContext>();
617 authResponseContext->reply = ERR_DM_AUTH_BUSINESS_BUSY;
618 authMessageProcessor->SetResponseContext(authResponseContext);
619 std::string message = authMessageProcessor->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
620 softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
621 softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId);
622 }
623 } else {
624 if (authResponseState_ == nullptr && authRequestState_ != nullptr &&
625 authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) {
626 authRequestContext_->sessionId = sessionId;
627 authResponseContext_->sessionId = sessionId;
628 authMessageProcessor_->SetRequestContext(authRequestContext_);
629 authRequestState_->SetAuthContext(authRequestContext_);
630 authRequestState_->TransitionTo(std::make_shared<AuthRequestNegotiateState>());
631 struct RadarInfo info = { .funcName = "OnSessionOpened" };
632 info.channelId = sessionId;
633 DmRadarHelper::GetInstance().ReportAuthSendRequest(info);
634 } else {
635 softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId);
636 LOGE("DmAuthManager::OnSessionOpened but request state is wrong");
637 }
638 }
639 }
640
OnSessionClosed(const int32_t sessionId)641 void DmAuthManager::OnSessionClosed(const int32_t sessionId)
642 {
643 LOGI("DmAuthManager::OnSessionClosed sessionId = %{public}d", sessionId);
644 if (authResponseState_ != nullptr) {
645 isFinishOfLocal_ = false;
646 authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
647 }
648 }
649
ProcessSourceMsg()650 void DmAuthManager::ProcessSourceMsg()
651 {
652 authRequestContext_ = authMessageProcessor_->GetRequestContext();
653 authRequestState_->SetAuthContext(authRequestContext_);
654 LOGI("OnDataReceived for source device, authResponseContext msgType = %{public}d, authRequestState stateType ="
655 "%{public}d", authResponseContext_->msgType, authRequestState_->GetStateType());
656
657 switch (authResponseContext_->msgType) {
658 case MSG_TYPE_RESP_AUTH:
659 case MSG_TYPE_RESP_AUTH_EXT:
660 if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
661 authRequestState_->TransitionTo(std::make_shared<AuthRequestReplyState>());
662 }
663 break;
664 case MSG_TYPE_RESP_NEGOTIATE:
665 if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE) {
666 authRequestState_->TransitionTo(std::make_shared<AuthRequestNegotiateDoneState>());
667 }
668 break;
669 case MSG_TYPE_REQ_AUTH_TERMINATE:
670 if (authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
671 isFinishOfLocal_ = false;
672 authResponseContext_->state = authRequestState_->GetStateType();
673 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
674 }
675 break;
676 case MSG_TYPE_RESP_PUBLICKEY:
677 if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_CREDENTIAL) {
678 authRequestState_->TransitionTo(std::make_shared<AuthRequestCredentialDone>());
679 }
680 break;
681 case MSG_TYPE_RESP_RECHECK_MSG:
682 if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_RECHECK_MSG) {
683 authRequestState_->TransitionTo(std::make_shared<AuthRequestReCheckMsgDone>());
684 }
685 break;
686 default:
687 break;
688 }
689 }
690
ProcessSinkMsg()691 void DmAuthManager::ProcessSinkMsg()
692 {
693 authResponseState_->SetAuthContext(authResponseContext_);
694 LOGI("OnDataReceived for sink device, authResponseContext msgType = %{public}d, authResponseState stateType ="
695 "%{public}d", authResponseContext_->msgType, authResponseState_->GetStateType());
696
697 switch (authResponseContext_->msgType) {
698 case MSG_TYPE_NEGOTIATE:
699 if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) {
700 if (timer_ != nullptr) {
701 timer_->DeleteTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK));
702 }
703 authResponseState_->TransitionTo(std::make_shared<AuthResponseNegotiateState>());
704 }
705 break;
706 case MSG_TYPE_REQ_AUTH:
707 if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) {
708 if (timer_ != nullptr) {
709 timer_->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK));
710 }
711 authResponseState_->TransitionTo(std::make_shared<AuthResponseConfirmState>());
712 }
713 break;
714 case MSG_TYPE_REQ_AUTH_TERMINATE:
715 if (authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) {
716 isFinishOfLocal_ = false;
717 authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
718 }
719 break;
720 case MSG_TYPE_REQ_PUBLICKEY:
721 ProcessReqPublicKey();
722 break;
723 case MSG_TYPE_REQ_RECHECK_MSG:
724 if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_AUTH_FINISH) {
725 authResponseState_->TransitionTo(std::make_shared<AuthResponseReCheckMsg>());
726 break;
727 }
728 if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) {
729 std::lock_guard<std::mutex> lock(srcReqMsgLock_);
730 isNeedProcCachedSrcReqMsg_ = true;
731 }
732 break;
733 default:
734 break;
735 }
736 }
737
OnDataReceived(const int32_t sessionId,const std::string message)738 void DmAuthManager::OnDataReceived(const int32_t sessionId, const std::string message)
739 {
740 if (authResponseContext_ == nullptr || authMessageProcessor_ == nullptr ||
741 sessionId != authResponseContext_->sessionId) {
742 LOGE("OnDataReceived failed, authResponseContext or authMessageProcessor_ is nullptr.");
743 return;
744 }
745
746 authResponseContext_->sessionId = sessionId;
747 authMessageProcessor_->SetResponseContext(authResponseContext_);
748 int32_t ret = authMessageProcessor_->ParseMessage(message);
749 if (ret != DM_OK) {
750 LOGE("OnDataReceived failed, parse input message error.");
751 return;
752 }
753
754 if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) {
755 // source device auth process
756 ProcessSourceMsg();
757 } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) {
758 // sink device auth process
759 {
760 std::lock_guard<std::mutex> lock(srcReqMsgLock_);
761 srcReqMsg_ = message;
762 }
763 ProcessSinkMsg();
764 } else {
765 LOGE("DmAuthManager::OnDataReceived failed, authRequestState_ or authResponseState_ is invalid.");
766 }
767 }
768
OnGroupCreated(int64_t requestId,const std::string & groupId)769 void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId)
770 {
771 if (authResponseContext_ == nullptr) {
772 LOGE("failed to OnGroupCreated because authResponseContext_ is nullptr");
773 return;
774 }
775 if (authResponseState_ == nullptr) {
776 LOGE("DmAuthManager::AuthenticateDevice end");
777 return;
778 }
779 LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str());
780 if (groupId == "{}") {
781 authResponseContext_->reply = ERR_DM_CREATE_GROUP_FAILED;
782 authMessageProcessor_->SetResponseContext(authResponseContext_);
783 std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
784 softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
785 return;
786 }
787
788 int32_t pinCode = -1;
789 if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) {
790 GetAuthCode(authResponseContext_->hostPkgName, pinCode);
791 } else if (authResponseContext_->authType != AUTH_TYPE_IMPORT_AUTH_CODE) {
792 pinCode = GeneratePincode();
793 } else {
794 LOGE("authType invalied.");
795 }
796 JsonObject jsonObj;
797 jsonObj[PIN_TOKEN] = authResponseContext_->token;
798 jsonObj[QR_CODE_KEY] = GenerateGroupName();
799 jsonObj[NFC_CODE_KEY] = GenerateGroupName();
800 authResponseContext_->authToken = SafetyDump(jsonObj);
801 LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str());
802 authResponseContext_->groupId = groupId;
803 authResponseContext_->code = pinCode;
804 authMessageProcessor_->SetResponseContext(authResponseContext_);
805 std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
806 softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
807 authResponseContext_->isFinish = true;
808 authResponseState_->TransitionTo(std::make_shared<AuthResponseShowState>());
809 }
810
OnMemberJoin(int64_t requestId,int32_t status)811 void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status)
812 {
813 isAddingMember_ = false;
814 if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) {
815 LOGE("failed to OnMemberJoin because authResponseContext_ or authUiStateMgr is nullptr");
816 return;
817 }
818 LOGI("DmAuthManager OnMemberJoin start authTimes %{public}d", authTimes_);
819 if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) {
820 MemberJoinAuthRequest(requestId, status);
821 } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) {
822 if (status == DM_OK && authResponseContext_->requestId == requestId &&
823 authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) {
824 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW);
825 } else {
826 if (++authTimes_ >= MAX_AUTH_TIMES) {
827 authResponseContext_->isFinish = false;
828 authResponseContext_->reply = ERR_DM_BIND_PIN_CODE_ERROR;
829 authResponseContext_->state = AuthState::AUTH_RESPONSE_SHOW;
830 isFinishOfLocal_ = false;
831 authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
832 }
833 }
834 } else {
835 LOGE("DmAuthManager::OnMemberJoin failed, authRequestState_ or authResponseState_ is invalid.");
836 }
837 }
838
MemberJoinAuthRequest(int64_t requestId,int32_t status)839 void DmAuthManager::MemberJoinAuthRequest(int64_t requestId, int32_t status)
840 {
841 authTimes_++;
842 if (timer_ != nullptr) {
843 timer_->DeleteTimer(std::string(ADD_TIMEOUT_TASK));
844 }
845 if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
846 HandleMemberJoinImportAuthCode(requestId, status);
847 return;
848 }
849 if (status != DM_OK || authResponseContext_->requestId != requestId) {
850 if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) {
851 authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN;
852 authResponseContext_->reply = ERR_DM_BIND_PIN_CODE_ERROR;
853 authRequestContext_->reason = ERR_DM_BIND_PIN_CODE_ERROR;
854 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
855 return;
856 }
857 if (timer_ != nullptr) {
858 timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK),
859 GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) {
860 DmAuthManager::HandleAuthenticateTimeout(name);
861 });
862 }
863 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR);
864 } else {
865 authRequestState_->TransitionTo(std::make_shared<AuthRequestNetworkState>());
866 if (timer_ != nullptr) {
867 timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK));
868 }
869 }
870 }
871
HandleMemberJoinImportAuthCode(const int64_t requestId,const int32_t status)872 void DmAuthManager::HandleMemberJoinImportAuthCode(const int64_t requestId, const int32_t status)
873 {
874 if (status != DM_OK || authResponseContext_->requestId != requestId) {
875 authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN;
876 authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT;
877 authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT;
878 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
879 } else {
880 authRequestState_->TransitionTo(std::make_shared<AuthRequestNetworkState>());
881 }
882 }
883
HandleAuthenticateTimeout(std::string name)884 void DmAuthManager::HandleAuthenticateTimeout(std::string name)
885 {
886 LOGI("DmAuthManager::HandleAuthenticateTimeout start timer name %{public}s", name.c_str());
887 if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
888 if (authResponseContext_ == nullptr) {
889 authResponseContext_ = std::make_shared<DmAuthResponseContext>();
890 }
891 authResponseContext_->state = authRequestState_->GetStateType();
892 authRequestContext_->reason = ERR_DM_TIME_OUT;
893 authResponseContext_->reply = ERR_DM_TIME_OUT;
894 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
895 }
896
897 if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) {
898 authResponseContext_->state = authResponseState_->GetStateType();
899 authResponseContext_->reply = ERR_DM_TIME_OUT;
900 authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
901 }
902 LOGI("DmAuthManager::HandleAuthenticateTimeout start complete");
903 }
904
EstablishAuthChannel(const std::string & deviceId)905 int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId)
906 {
907 int32_t sessionId = 0;
908 if (IsHmlSessionType()) {
909 CHECK_NULL_RETURN(authRequestContext_, ERR_DM_FAILED);
910 LOGI("hmlActionId %{public}d, hmlReleaseTime %{public}d, hmlEnable160M %{public}d",
911 authRequestContext_->hmlActionId, authRequestContext_->closeSessionDelaySeconds,
912 authRequestContext_->hmlEnable160M);
913 sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSessionWithPara(deviceId,
914 authRequestContext_->hmlActionId, authRequestContext_->hmlEnable160M);
915 } else {
916 sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId);
917 }
918 struct RadarInfo info = {
919 .funcName = "EstablishAuthChannel",
920 .stageRes = (sessionId > 0) ?
921 static_cast<int32_t>(StageRes::STAGE_IDLE) : static_cast<int32_t>(StageRes::STAGE_FAIL),
922 .bizState = (sessionId > 0) ?
923 static_cast<int32_t>(BizState::BIZ_STATE_START) : static_cast<int32_t>(BizState::BIZ_STATE_END),
924 .localSessName = DM_SESSION_NAME,
925 .peerSessName = DM_SESSION_NAME,
926 .isTrust = static_cast<int32_t>(TrustStatus::NOT_TRUST),
927 .commServ = static_cast<int32_t>(CommServ::USE_SOFTBUS),
928 .peerUdid = peerTargetId_.deviceId,
929 .channelId = sessionId,
930 .errCode = sessionId,
931 };
932 if (!DmRadarHelper::GetInstance().ReportAuthOpenSession(info)) {
933 LOGE("ReportAuthOpenSession failed");
934 }
935 if (sessionId < 0) {
936 LOGE("OpenAuthSession failed, stop the authentication");
937 if (authResponseContext_ == nullptr) {
938 authResponseContext_ = std::make_shared<DmAuthResponseContext>();
939 }
940 authResponseContext_->state = AuthState::AUTH_REQUEST_NEGOTIATE;
941 authResponseContext_->reply = sessionId;
942 if (authRequestContext_ == nullptr) {
943 authRequestContext_ = std::make_shared<DmAuthRequestContext>();
944 }
945 authRequestContext_->reason = sessionId;
946 if (authRequestState_ != nullptr) {
947 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
948 }
949 }
950 return DM_OK;
951 }
952
StartNegotiate(const int32_t & sessionId)953 void DmAuthManager::StartNegotiate(const int32_t &sessionId)
954 {
955 if (authResponseContext_ == nullptr) {
956 LOGE("DmAuthManager::StartNegotiate error, authResponseContext_ is nullptr");
957 return;
958 }
959 LOGI("DmAuthManager::StartNegotiate sessionId %{public}d.", sessionId);
960 authResponseContext_->localDeviceId = authRequestContext_->localDeviceId;
961 authResponseContext_->reply = ERR_DM_AUTH_REJECT;
962 authResponseContext_->authType = authRequestContext_->authType;
963 authResponseContext_->deviceId = authRequestContext_->deviceId;
964 authResponseContext_->accountGroupIdHash = GetAccountGroupIdHash();
965 authResponseContext_->hostPkgName = authRequestContext_->hostPkgName;
966 authResponseContext_->bundleName = authRequestContext_->bundleName;
967 authResponseContext_->peerBundleName = authRequestContext_->peerBundleName;
968 authResponseContext_->hostPkgLabel = authRequestContext_->hostPkgLabel;
969 authResponseContext_->tokenId = authRequestContext_->tokenId;
970 authResponseContext_->bindLevel = authRequestContext_->bindLevel;
971 authResponseContext_->bindType = authRequestContext_->bindType;
972 authResponseContext_->isOnline = authRequestContext_->isOnline;
973 authResponseContext_->authed = authRequestContext_->authed;
974 authResponseContext_->dmVersion = "";
975 authResponseContext_->localAccountId = authRequestContext_->localAccountId;
976 authResponseContext_->localUserId = authRequestContext_->localUserId;
977 authResponseContext_->isIdenticalAccount = false;
978 authResponseContext_->edition = DM_VERSION_5_0_5;
979 authResponseContext_->remoteDeviceName = authRequestContext_->localDeviceName;
980 authMessageProcessor_->SetResponseContext(authResponseContext_);
981 std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE);
982 softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
983 if (timer_ != nullptr) {
984 timer_->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK),
985 GetTaskTimeout(NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), [this] (std::string name) {
986 DmAuthManager::HandleAuthenticateTimeout(name);
987 });
988 }
989 }
990
AbilityNegotiate()991 void DmAuthManager::AbilityNegotiate()
992 {
993 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
994 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
995 authResponseContext_->remoteAccountId = authResponseContext_->localAccountId;
996 authResponseContext_->remoteUserId = authResponseContext_->localUserId;
997 GetBinderInfo();
998 bool ret = hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, localDeviceId);
999 if (ret) {
1000 LOGE("DmAuthManager::EstablishAuthChannel device is in group");
1001 if (!DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(authResponseContext_->hostPkgName,
1002 authResponseContext_->localDeviceId)) {
1003 CompatiblePutAcl();
1004 }
1005 authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT;
1006 if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_3)) &&
1007 authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) {
1008 authResponseContext_->importAuthCode = Crypto::Sha256(importAuthCode_);
1009 }
1010 } else {
1011 authResponseContext_->reply = ERR_DM_AUTH_REJECT;
1012 }
1013 authResponseContext_->localDeviceId = localDeviceId;
1014
1015 if (!IsAuthTypeSupported(authResponseContext_->authType)) {
1016 LOGE("DmAuthManager::AuthenticateDevice authType %{public}d not support.", authResponseContext_->authType);
1017 authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE;
1018 } else {
1019 authPtr_ = authenticationMap_[authResponseContext_->authType];
1020 }
1021
1022 if (IsAuthCodeReady(authResponseContext_->hostPkgName)) {
1023 authResponseContext_->isAuthCodeReady = true;
1024 } else {
1025 authResponseContext_->isAuthCodeReady = false;
1026 }
1027 }
1028
RespNegotiate(const int32_t & sessionId)1029 void DmAuthManager::RespNegotiate(const int32_t &sessionId)
1030 {
1031 if (authResponseContext_ == nullptr || authRequestState_ != nullptr) {
1032 LOGE("failed to RespNegotiate because authResponseContext_ is nullptr");
1033 return;
1034 }
1035 LOGI("DmAuthManager::RespNegotiate sessionid %{public}d", sessionId);
1036 remoteDeviceId_ = authResponseContext_->localDeviceId;
1037 authResponseContext_->networkId = softbusConnector_->GetLocalDeviceNetworkId();
1038 authResponseContext_->targetDeviceName = softbusConnector_->GetLocalDeviceName();
1039 remoteVersion_ = ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition);
1040 NegotiateRespMsg(remoteVersion_);
1041 if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1042 (static_cast<uint32_t>(authResponseContext_->bindLevel) >= DEVICE &&
1043 static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
1044 ProcRespNegotiateExt(sessionId);
1045 timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK),
1046 GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) {
1047 DmAuthManager::HandleAuthenticateTimeout(name);
1048 });
1049 } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
1050 authResponseContext_->bindLevel == INVALIED_TYPE) {
1051 ProcRespNegotiate(sessionId);
1052 timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK),
1053 GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) {
1054 DmAuthManager::HandleAuthenticateTimeout(name);
1055 });
1056 } else {
1057 ProcIncompatible(sessionId);
1058 }
1059 }
1060
NegotiateRespMsg(const std::string & version)1061 void DmAuthManager::NegotiateRespMsg(const std::string &version)
1062 {
1063 if (version == DM_VERSION_5_0_1) {
1064 authResponseContext_->dmVersion = DM_VERSION_5_0_1;
1065 } else if (version < DM_VERSION_5_0_1) {
1066 authResponseContext_->dmVersion = "";
1067 authResponseContext_->bindLevel = INVALIED_TYPE;
1068 } else if (version > DM_VERSION_5_0_1) {
1069 authResponseContext_->dmVersion = dmVersion_;
1070 }
1071 }
1072
SendAuthRequest(const int32_t & sessionId)1073 void DmAuthManager::SendAuthRequest(const int32_t &sessionId)
1074 {
1075 LOGI("DmAuthManager::SendAuthRequest sessionId %{public}d.", sessionId);
1076 if (authResponseContext_ == nullptr) {
1077 LOGE("failed to SendAuthRequest because authResponseContext_ is nullptr");
1078 return;
1079 }
1080 if (authResponseContext_->reply == ERR_DM_VERSION_INCOMPATIBLE) {
1081 LOGE("The peer device version is not supported");
1082 authRequestContext_->reason = authResponseContext_->reply;
1083 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1084 return;
1085 }
1086 remoteDeviceId_ = authResponseContext_->localDeviceId;
1087 authRequestContext_->remoteDeviceName = authResponseContext_->targetDeviceName;
1088 remoteVersion_ = ConvertSinkVersion(authResponseContext_->dmVersion);
1089 if (timer_ != nullptr) {
1090 timer_->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK));
1091 }
1092 if (authResponseContext_->cryptoSupport) {
1093 isCryptoSupport_ = true;
1094 }
1095 LOGI("SendAuthRequest dmversion %{public}s, level %{public}d",
1096 authResponseContext_->dmVersion.c_str(), authResponseContext_->bindLevel);
1097 if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1098 (static_cast<uint32_t>(authResponseContext_->bindLevel) >= DEVICE &&
1099 static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
1100 ProcessAuthRequestExt(sessionId);
1101 } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
1102 authResponseContext_->bindLevel == INVALIED_TYPE) {
1103 ProcessAuthRequest(sessionId);
1104 } else {
1105 LOGE("Invalied bind mode.");
1106 }
1107 }
1108
ProcessAuthRequest(const int32_t & sessionId)1109 void DmAuthManager::ProcessAuthRequest(const int32_t &sessionId)
1110 {
1111 LOGI("ProcessAuthRequest start.");
1112 if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
1113 !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) {
1114 if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) {
1115 SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH);
1116 return;
1117 }
1118 }
1119
1120 if (authResponseContext_->isOnline && softbusConnector_->CheckIsOnline(remoteDeviceId_)) {
1121 authResponseContext_->isOnline = true;
1122 } else {
1123 authResponseContext_->isOnline = false;
1124 }
1125 if (CheckTrustState() != DM_OK) {
1126 LOGI("CheckTrustState end.");
1127 return;
1128 }
1129
1130 std::vector<std::string> messageList = authMessageProcessor_->CreateAuthRequestMessage();
1131 for (auto msg : messageList) {
1132 softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg);
1133 }
1134
1135 listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token,
1136 STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK);
1137 listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, "");
1138 timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK),
1139 GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) {
1140 DmAuthManager::HandleAuthenticateTimeout(name);
1141 });
1142 }
1143
GetAuthRequestContext()1144 void DmAuthManager::GetAuthRequestContext()
1145 {
1146 char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0};
1147 Crypto::GetUdidHash(authResponseContext_->localDeviceId, reinterpret_cast<uint8_t *>(deviceIdHash));
1148 authRequestContext_->deviceId = static_cast<std::string>(deviceIdHash);
1149 authResponseContext_->deviceId = authResponseContext_->localDeviceId;
1150 authResponseContext_->localDeviceId = authRequestContext_->localDeviceId;
1151 authRequestContext_->remoteAccountId = authResponseContext_->localAccountId;
1152 authResponseContext_->remoteAccountId = authRequestContext_->remoteAccountId;
1153 authResponseContext_->localAccountId = authRequestContext_->localAccountId;
1154 authRequestContext_->remoteUserId = authResponseContext_->localUserId;
1155 if (authResponseContext_->isOnline && softbusConnector_->CheckIsOnline(remoteDeviceId_)) {
1156 authResponseContext_->isOnline = true;
1157 } else {
1158 authResponseContext_->isOnline = false;
1159 }
1160 authResponseContext_->haveCredential = false;
1161 }
1162
ProcessAuthRequestExt(const int32_t & sessionId)1163 void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId)
1164 {
1165 LOGI("ProcessAuthRequestExt start.");
1166 if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_3)) &&
1167 authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
1168 !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) {
1169 if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) {
1170 SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH);
1171 return;
1172 }
1173 }
1174
1175 GetAuthRequestContext();
1176 std::vector<int32_t> bindType =
1177 DeviceProfileConnector::GetInstance().SyncAclByBindType(authResponseContext_->hostPkgName,
1178 authResponseContext_->bindType, authResponseContext_->localDeviceId, authResponseContext_->deviceId);
1179 authResponseContext_->authed = !bindType.empty();
1180 if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_3)) &&
1181 authResponseContext_->isOnline && authResponseContext_->authed &&
1182 authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
1183 (authResponseContext_->importAuthCode.empty() || importAuthCode_.empty())) {
1184 SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH);
1185 return;
1186 }
1187 authResponseContext_->bindType = bindType;
1188 if (IsAuthFinish()) {
1189 return;
1190 }
1191
1192 std::vector<std::string> messageList = authMessageProcessor_->CreateAuthRequestMessage();
1193 for (auto msg : messageList) {
1194 softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg);
1195 }
1196 listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token,
1197 STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK);
1198 listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, "");
1199 timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK),
1200 GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) {
1201 DmAuthManager::HandleAuthenticateTimeout(name);
1202 });
1203 }
1204
IsAuthFinish()1205 bool DmAuthManager::IsAuthFinish()
1206 {
1207 if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE) {
1208 listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId,
1209 authRequestContext_->token, AuthState::AUTH_REQUEST_NEGOTIATE_DONE, ERR_DM_UNSUPPORTED_AUTH_TYPE);
1210 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1211 return true;
1212 }
1213
1214 if ((authResponseContext_->isIdenticalAccount && !authResponseContext_->authed) ||
1215 (authResponseContext_->authed && !authResponseContext_->isOnline)) {
1216 JoinLnn(authRequestContext_->addr);
1217 authRequestContext_->reason = DM_OK;
1218 authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
1219 authResponseContext_->reply = DM_OK;
1220 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1221 return true;
1222 }
1223
1224 if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE ||
1225 (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
1226 authResponseContext_->isAuthCodeReady == false)) {
1227 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1228 return true;
1229 }
1230 return false;
1231 }
1232
ConfirmProcess(const int32_t & action)1233 int32_t DmAuthManager::ConfirmProcess(const int32_t &action)
1234 {
1235 LOGI("ConfirmProcess start.");
1236 if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH || action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
1237 authResponseContext_->reply = USER_OPERATION_TYPE_ALLOW_AUTH;
1238 } else {
1239 authResponseContext_->reply = action_;
1240 }
1241
1242 if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH &&
1243 authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) {
1244 authResponseState_->TransitionTo(std::make_shared<AuthResponseGroupState>());
1245 } else {
1246 authMessageProcessor_->SetResponseContext(authResponseContext_);
1247 std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH);
1248 softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1249 }
1250 return DM_OK;
1251 }
1252
ConfirmProcessExt(const int32_t & action)1253 int32_t DmAuthManager::ConfirmProcessExt(const int32_t &action)
1254 {
1255 LOGI("ConfirmProcessExt start.");
1256 authResponseContext_->confirmOperation = action;
1257 if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH || action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
1258 authResponseContext_->reply = USER_OPERATION_TYPE_ALLOW_AUTH;
1259 } else {
1260 authResponseContext_->reply = USER_OPERATION_TYPE_CANCEL_AUTH;
1261 }
1262 authMessageProcessor_->SetResponseContext(authResponseContext_);
1263 if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH &&
1264 authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_CONFIRM) {
1265 if (CanUsePincodeFromDp()) {
1266 authResponseContext_->code = std::atoi(serviceInfoProfile_.GetPinCode().c_str());
1267 LOGI("import pincode from dp");
1268 } else if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) {
1269 GetAuthCode(authResponseContext_->hostPkgName, authResponseContext_->code);
1270 } else {
1271 authResponseContext_->code = GeneratePincode();
1272 }
1273 authResponseContext_->requestId = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE);
1274 authResponseState_->TransitionTo(std::make_shared<AuthResponseShowState>());
1275 }
1276 authMessageProcessor_->SetResponseContext(authResponseContext_);
1277 std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH_EXT);
1278 softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1279 return DM_OK;
1280 }
1281
StartAuthProcess(const int32_t & action)1282 int32_t DmAuthManager::StartAuthProcess(const int32_t &action)
1283 {
1284 if (authResponseContext_ == nullptr) {
1285 LOGE("failed to StartAuthProcess because authResponseContext_ is nullptr");
1286 return ERR_DM_AUTH_NOT_START;
1287 }
1288 LOGI("DmAuthManager::StartAuthProcess");
1289 action_ = action;
1290 struct RadarInfo info = {
1291 .funcName = "StartAuthProcess",
1292 .stageRes = (action_ == USER_OPERATION_TYPE_CANCEL_AUTH) ?
1293 static_cast<int32_t>(StageRes::STAGE_CANCEL) : static_cast<int32_t>(StageRes::STAGE_SUCC),
1294 .bizState = (action_ == USER_OPERATION_TYPE_CANCEL_AUTH) ?
1295 static_cast<int32_t>(BizState::BIZ_STATE_END) : static_cast<int32_t>(BizState::BIZ_STATE_START),
1296 .errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_AUTH_REJECT),
1297 };
1298 if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) {
1299 LOGE("ReportAuthConfirmBox failed");
1300 }
1301 if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1302 (static_cast<uint32_t>(authResponseContext_->bindLevel) >= DEVICE &&
1303 static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
1304 return ConfirmProcessExt(action);
1305 } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
1306 authResponseContext_->bindLevel == INVALIED_TYPE) {
1307 return ConfirmProcess(action);
1308 } else {
1309 LOGE("Invalied bind mode.");
1310 }
1311 return DM_OK;
1312 }
1313
StartRespAuthProcess()1314 void DmAuthManager::StartRespAuthProcess()
1315 {
1316 if (authResponseContext_ == nullptr) {
1317 LOGE("failed to StartRespAuthProcess because authResponseContext_ is nullptr");
1318 return;
1319 }
1320 LOGI("DmAuthManager::StartRespAuthProcess sessionId = %{public}d", authResponseContext_->sessionId);
1321 if (timer_ != nullptr) {
1322 timer_->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK));
1323 }
1324 if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ALWAYS) {
1325 action_ = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS;
1326 } else if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ONCE) {
1327 action_ = USER_OPERATION_TYPE_ALLOW_AUTH;
1328 }
1329 if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH) {
1330 timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK),
1331 GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) {
1332 DmAuthManager::HandleAuthenticateTimeout(name);
1333 });
1334 timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK),
1335 GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) {
1336 DmAuthManager::HandleSessionHeartbeat(name);
1337 });
1338 listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId,
1339 authRequestContext_->token, STATUS_DM_SHOW_PIN_INPUT_UI, DM_OK);
1340 listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_PIN_INPUT_UI, "");
1341 authRequestState_->TransitionTo(std::make_shared<AuthRequestJoinState>());
1342 } else {
1343 LOGE("do not accept");
1344 authResponseContext_->state = AuthState::AUTH_REQUEST_REPLY;
1345 authRequestContext_->reason = ERR_DM_AUTH_PEER_REJECT;
1346 authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT;
1347 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1348 }
1349 }
1350
CreateGroup()1351 int32_t DmAuthManager::CreateGroup()
1352 {
1353 if (authResponseContext_ == nullptr) {
1354 LOGE("failed to CreateGroup because authResponseContext_ is nullptr");
1355 return ERR_DM_FAILED;
1356 }
1357 LOGI("DmAuthManager::CreateGroup start");
1358 authResponseContext_->groupName = GenerateGroupName();
1359 authResponseContext_->requestId = GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID);
1360 hiChainConnector_->CreateGroup(authResponseContext_->requestId, authResponseContext_->groupName);
1361 return DM_OK;
1362 }
1363
AddMember(int32_t pinCode)1364 int32_t DmAuthManager::AddMember(int32_t pinCode)
1365 {
1366 if (authResponseContext_ == nullptr) {
1367 LOGE("failed to AddMember because authResponseContext_ is nullptr");
1368 return ERR_DM_FAILED;
1369 }
1370 LOGI("DmAuthManager::AddMember start group id %{public}s", GetAnonyString(authResponseContext_->groupId).c_str());
1371 if (timer_ != nullptr) {
1372 timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK));
1373 }
1374 JsonObject jsonObject;
1375 jsonObject[TAG_GROUP_ID] = authResponseContext_->groupId;
1376 jsonObject[TAG_GROUP_NAME] = authResponseContext_->groupName;
1377 jsonObject[PIN_CODE_KEY] = pinCode;
1378 jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId;
1379 jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId;
1380 std::string connectInfo = SafetyDump(jsonObject);
1381 if (timer_ != nullptr) {
1382 timer_->StartTimer(std::string(ADD_TIMEOUT_TASK),
1383 GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) {
1384 DmAuthManager::HandleAuthenticateTimeout(name);
1385 });
1386 }
1387 if (authUiStateMgr_ == nullptr) {
1388 LOGE("DmAuthManager::AddMember authUiStateMgr is null.");
1389 return ERR_DM_FAILED;
1390 }
1391 if (isAddingMember_) {
1392 LOGE("DmAuthManager::AddMember doing add member.");
1393 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_DOING_AUTH);
1394 return ERR_DM_FAILED;
1395 }
1396 isAddingMember_ = true;
1397 int32_t ret = hiChainConnector_->AddMember(authRequestContext_->addr, connectInfo);
1398 struct RadarInfo info = {
1399 .funcName = "AddMember",
1400 .stageRes = (ret == 0) ?
1401 static_cast<int32_t>(StageRes::STAGE_IDLE) : static_cast<int32_t>(StageRes::STAGE_FAIL),
1402 .peerUdid = authResponseContext_ == nullptr ? "" : authResponseContext_->deviceId,
1403 .errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_ADD_GROUP_FAILED),
1404 };
1405 if (!DmRadarHelper::GetInstance().ReportAuthAddGroup(info)) {
1406 LOGE("ReportAuthAddGroup failed");
1407 }
1408 if (ret != 0) {
1409 LOGE("DmAuthManager::AddMember failed, ret: %{public}d", ret);
1410 isAddingMember_ = false;
1411 return ERR_DM_ADD_GROUP_FAILED;
1412 }
1413 return DM_OK;
1414 }
1415
GetConnectAddr(std::string deviceId)1416 std::string DmAuthManager::GetConnectAddr(std::string deviceId)
1417 {
1418 std::string connectAddr;
1419 if (softbusConnector_->GetConnectAddr(deviceId, connectAddr) == nullptr) {
1420 LOGE("DmAuthManager::GetConnectAddr error");
1421 }
1422 return connectAddr;
1423 }
1424
JoinNetwork()1425 int32_t DmAuthManager::JoinNetwork()
1426 {
1427 if (authResponseContext_ == nullptr) {
1428 LOGE("failed to JoinNeWork because authResponseContext_ is nullptr");
1429 return ERR_DM_FAILED;
1430 }
1431 LOGI("DmAuthManager JoinNetwork start");
1432 if (timer_ != nullptr) {
1433 timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK));
1434 }
1435 authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
1436 authResponseContext_->isFinish = true;
1437 authRequestContext_->reason = DM_OK;
1438 authResponseContext_->reply = DM_OK;
1439 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1440 return DM_OK;
1441 }
1442
SinkAuthenticateFinish()1443 void DmAuthManager::SinkAuthenticateFinish()
1444 {
1445 LOGI("DmAuthManager::SinkAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_);
1446 processInfo_.pkgName = authResponseContext_->peerBundleName;
1447 listener_->OnSinkBindResult(processInfo_, peerTargetId_, authResponseContext_->reply,
1448 authResponseContext_->state, GenerateBindResultContent());
1449 if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH &&
1450 (authResponseContext_->authType == AUTH_TYPE_NFC || authPtr_ != nullptr)) {
1451 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW);
1452 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_CONFIRM_SHOW);
1453 }
1454 if (isFinishOfLocal_) {
1455 authMessageProcessor_->SetResponseContext(authResponseContext_);
1456 std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
1457 softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1458 }
1459 authResponseState_ = nullptr;
1460 authTimes_ = 0;
1461 }
1462
SrcAuthenticateFinish()1463 void DmAuthManager::SrcAuthenticateFinish()
1464 {
1465 LOGI("DmAuthManager::SrcAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_);
1466 if (isFinishOfLocal_) {
1467 authMessageProcessor_->SetResponseContext(authResponseContext_);
1468 std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_AUTH_TERMINATE);
1469 softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
1470 } else {
1471 authRequestContext_->reason = authResponseContext_->reply;
1472 }
1473 if ((authResponseContext_->state == AuthState::AUTH_REQUEST_JOIN ||
1474 authResponseContext_->state == AuthState::AUTH_REQUEST_FINISH) &&
1475 (authResponseContext_->authType == AUTH_TYPE_NFC || authPtr_ != nullptr)) {
1476 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT);
1477 }
1478 if (timer_ == nullptr) {
1479 timer_ = std::make_shared<DmTimer>();
1480 }
1481 int32_t closeSessionDelaySeconds = authRequestContext_->closeSessionDelaySeconds;
1482 if (IsHmlSessionType() && closeSessionDelaySeconds == 0 && isWaitingJoinLnnCallback_) {
1483 closeSessionDelaySeconds = SESSION_CLOSE_TIMEOUT;
1484 }
1485 timer_->StartTimer(std::string(WAIT_SESSION_CLOSE_TIMEOUT_TASK) + std::string(CLOSE_SESSION_TASK_SEPARATOR) +
1486 std::to_string(authRequestContext_->sessionId),
1487 closeSessionDelaySeconds, [this] (std::string name) {
1488 int32_t sessionIdIndex = 1;
1489 std::string sessionStr = GetSubStr(name, std::string(CLOSE_SESSION_TASK_SEPARATOR), sessionIdIndex);
1490 if (!sessionStr.empty()) {
1491 int32_t sessionId = std::atoi(sessionStr.c_str());
1492 DmAuthManager::CloseAuthSession(sessionId);
1493 }
1494 });
1495 listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token,
1496 authResponseContext_->state, authRequestContext_->reason);
1497 listener_->OnBindResult(processInfo_, peerTargetId_, authRequestContext_->reason,
1498 authResponseContext_->state, GenerateBindResultContent());
1499
1500 authRequestContext_ = nullptr;
1501 authRequestState_ = nullptr;
1502 authTimes_ = 0;
1503 isWaitingJoinLnnCallback_ = false;
1504 }
1505
AuthenticateFinish()1506 void DmAuthManager::AuthenticateFinish()
1507 {
1508 {
1509 std::lock_guard<std::mutex> lock(srcReqMsgLock_);
1510 srcReqMsg_ = "";
1511 isNeedProcCachedSrcReqMsg_ = false;
1512 std::lock_guard<std::mutex> guard(sessionKeyIdMutex_);
1513 sessionKeyIdAsyncResult_.clear();
1514 }
1515 pincodeDialogEverShown_ = false;
1516 serviceInfoProfile_ = {};
1517 authType_ = AUTH_TYPE_UNKNOW;
1518 std::lock_guard<std::mutex> autoLock(g_authFinishLock);
1519 if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) {
1520 LOGE("failed to AuthenticateFinish because authResponseContext_ or authUiStateMgr is nullptr");
1521 return;
1522 }
1523 LOGI("DmAuthManager::AuthenticateFinish start");
1524 isAddingMember_ = false;
1525 isAuthenticateDevice_ = false;
1526 isAuthDevice_ = false;
1527 if (authResponseContext_->isFinish) {
1528 CompatiblePutAcl();
1529 }
1530 if (DeviceProfileConnector::GetInstance().GetTrustNumber(remoteDeviceId_) >= 1 &&
1531 CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1532 softbusConnector_->CheckIsOnline(remoteDeviceId_) && authResponseContext_->isFinish) {
1533 softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_);
1534 }
1535
1536 DeleteAuthCode();
1537 if (timer_ != nullptr) {
1538 timer_->DeleteAll();
1539 }
1540 if (authResponseState_ != nullptr) {
1541 SinkAuthenticateFinish();
1542 } else if (authRequestState_ != nullptr) {
1543 SrcAuthenticateFinish();
1544 }
1545 isFinishOfLocal_ = true;
1546 authResponseContext_ = nullptr;
1547 authMessageProcessor_ = nullptr;
1548 authPtr_ = nullptr;
1549 authRequestStateTemp_ = nullptr;
1550 authenticationType_ = USER_OPERATION_TYPE_ALLOW_AUTH;
1551 bundleName_ = "";
1552 LOGI("DmAuthManager::AuthenticateFinish complete");
1553 }
1554
RegisterUiStateCallback(const std::string pkgName)1555 int32_t DmAuthManager::RegisterUiStateCallback(const std::string pkgName)
1556 {
1557 LOGI("DmAuthManager::RegisterUiStateCallback start");
1558 if (authUiStateMgr_ == nullptr) {
1559 LOGE("DmAuthManager::RegisterUiStateCallback authUiStateMgr_ is null.");
1560 return ERR_DM_FAILED;
1561 }
1562 authUiStateMgr_->RegisterUiStateCallback(pkgName);
1563 return DM_OK;
1564 }
1565
UnRegisterUiStateCallback(const std::string pkgName)1566 int32_t DmAuthManager::UnRegisterUiStateCallback(const std::string pkgName)
1567 {
1568 LOGI("DmAuthManager::UnRegisterUiStateCallback start");
1569 if (authUiStateMgr_ == nullptr) {
1570 LOGE("DmAuthManager::UnRegisterUiStateCallback authUiStateMgr_ is null.");
1571 return ERR_DM_FAILED;
1572 }
1573 authUiStateMgr_->UnRegisterUiStateCallback(pkgName);
1574 return DM_OK;
1575 }
1576
GeneratePincode()1577 int32_t DmAuthManager::GeneratePincode()
1578 {
1579 return GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE);
1580 }
1581
IsPinCodeValid(const std::string strpin)1582 bool DmAuthManager::IsPinCodeValid(const std::string strpin)
1583 {
1584 if (strpin.empty()) {
1585 return false;
1586 }
1587 for (size_t i = 0; i < strpin.length(); i++) {
1588 if (!isdigit(strpin[i])) {
1589 return false;
1590 }
1591 }
1592 int32_t pinnum = std::atoi(strpin.c_str());
1593 return IsPinCodeValid(pinnum);
1594 }
1595
IsPinCodeValid(int32_t numpin)1596 bool DmAuthManager::IsPinCodeValid(int32_t numpin)
1597 {
1598 if (numpin < MIN_PIN_CODE || numpin > MAX_PIN_CODE) {
1599 return false;
1600 }
1601 return true;
1602 }
1603
CanUsePincodeFromDp()1604 bool DmAuthManager::CanUsePincodeFromDp()
1605 {
1606 CHECK_NULL_RETURN(authResponseContext_, false);
1607 return (IsPinCodeValid(serviceInfoProfile_.GetPinCode()) &&
1608 serviceInfoProfile_.GetPinExchangeType() == (int32_t)DMLocalServiceInfoPinExchangeType::FROMDP);
1609 }
1610
IsServiceInfoAuthTypeValid(int32_t authType)1611 bool DmAuthManager::IsServiceInfoAuthTypeValid(int32_t authType)
1612 {
1613 if (authType != (int32_t)DMLocalServiceInfoAuthType::TRUST_ONETIME &&
1614 authType != (int32_t)DMLocalServiceInfoAuthType::TRUST_ALWAYS &&
1615 authType != (int32_t)DMLocalServiceInfoAuthType::CANCEL) {
1616 return false;
1617 }
1618 return true;
1619 }
1620
IsServiceInfoAuthBoxTypeValid(int32_t authBoxType)1621 bool DmAuthManager::IsServiceInfoAuthBoxTypeValid(int32_t authBoxType)
1622 {
1623 if (authBoxType != (int32_t)DMLocalServiceInfoAuthBoxType::STATE3 &&
1624 authBoxType != (int32_t)DMLocalServiceInfoAuthBoxType::SKIP_CONFIRM) {
1625 return false;
1626 }
1627 return true;
1628 }
1629
IsServiceInfoPinExchangeTypeValid(int32_t pinExchangeType)1630 bool DmAuthManager::IsServiceInfoPinExchangeTypeValid(int32_t pinExchangeType)
1631 {
1632 if (pinExchangeType != (int32_t)DMLocalServiceInfoPinExchangeType::PINBOX &&
1633 pinExchangeType != (int32_t)DMLocalServiceInfoPinExchangeType::FROMDP &&
1634 pinExchangeType != (int32_t)DMLocalServiceInfoPinExchangeType::ULTRASOUND) {
1635 return false;
1636 }
1637 return true;
1638 }
1639
IsLocalServiceInfoValid(const DistributedDeviceProfile::LocalServiceInfo & localServiceInfo)1640 bool DmAuthManager::IsLocalServiceInfoValid(const DistributedDeviceProfile::LocalServiceInfo &localServiceInfo)
1641 {
1642 if (!IsServiceInfoAuthTypeValid(localServiceInfo.GetAuthType())) {
1643 LOGE("AuthType not valid, %{public}d", localServiceInfo.GetAuthType());
1644 return false;
1645 }
1646 if (!IsServiceInfoAuthBoxTypeValid(localServiceInfo.GetAuthBoxType())) {
1647 LOGE("AuthBoxType not valid, %{public}d", localServiceInfo.GetAuthBoxType());
1648 return false;
1649 }
1650 if (!IsServiceInfoPinExchangeTypeValid(localServiceInfo.GetPinExchangeType())) {
1651 LOGE("PinExchangeType not valid, %{public}d", localServiceInfo.GetPinExchangeType());
1652 return false;
1653 }
1654 return true;
1655 }
1656
GenerateGroupName()1657 std::string DmAuthManager::GenerateGroupName()
1658 {
1659 if (authResponseContext_ == nullptr) {
1660 LOGE("failed to GenerateGroupName because authResponseContext_ is nullptr.");
1661 return "";
1662 }
1663 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
1664 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
1665 std::string sLocalDeviceId = localDeviceId;
1666 uint32_t interceptLength = sLocalDeviceId.size() / DEVICE_ID_HALF;
1667 std::string groupName = "";
1668 if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
1669 groupName += AUTH_ALWAYS;
1670 } else {
1671 groupName += AUTH_ONCE;
1672 }
1673 groupName += authResponseContext_->targetPkgName + sLocalDeviceId.substr(0, interceptLength)
1674 + authResponseContext_->localDeviceId.substr(0, interceptLength);
1675 return groupName;
1676 }
1677
GetIsCryptoSupport()1678 bool DmAuthManager::GetIsCryptoSupport()
1679 {
1680 if (authResponseState_ == nullptr) {
1681 return false;
1682 }
1683 if (authRequestState_ == nullptr) {
1684 if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
1685 return false;
1686 }
1687 } else {
1688 if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE ||
1689 authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
1690 return false;
1691 }
1692 }
1693
1694 return isCryptoSupport_;
1695 }
1696
SetAuthRequestState(std::shared_ptr<AuthRequestState> authRequestState)1697 int32_t DmAuthManager::SetAuthRequestState(std::shared_ptr<AuthRequestState> authRequestState)
1698 {
1699 if (authRequestState == nullptr) {
1700 LOGE("authRequestState is nullptr.");
1701 return ERR_DM_INPUT_PARA_INVALID;
1702 }
1703 // Keep current state, avoid deconstructed during state transitions
1704 authRequestStateTemp_ = authRequestState_;
1705 authRequestState_ = authRequestState;
1706 return DM_OK;
1707 }
1708
SetAuthResponseState(std::shared_ptr<AuthResponseState> authResponseState)1709 int32_t DmAuthManager::SetAuthResponseState(std::shared_ptr<AuthResponseState> authResponseState)
1710 {
1711 if (authResponseState == nullptr) {
1712 LOGE("authResponseState is nullptr.");
1713 return ERR_DM_INPUT_PARA_INVALID;
1714 }
1715 authResponseState_ = authResponseState;
1716 return DM_OK;
1717 }
1718
GetPinCode(int32_t & code)1719 int32_t DmAuthManager::GetPinCode(int32_t &code)
1720 {
1721 if (authResponseContext_ == nullptr) {
1722 LOGE("failed to GetPinCode because authResponseContext_ is nullptr");
1723 return ERR_DM_FAILED;
1724 }
1725 LOGI("ShowConfigDialog start add member pin code.");
1726 code = authResponseContext_->code;
1727 return DM_OK;
1728 }
1729
ShowConfigDialog()1730 void DmAuthManager::ShowConfigDialog()
1731 {
1732 if (authResponseContext_ == nullptr) {
1733 LOGE("failed to ShowConfigDialog because authResponseContext_ is nullptr");
1734 return;
1735 }
1736 if (authResponseContext_->authType == AUTH_TYPE_NFC &&
1737 serviceInfoProfile_.GetAuthBoxType() == (int32_t)DMLocalServiceInfoAuthBoxType::SKIP_CONFIRM) {
1738 LOGI("no need confirm dialog");
1739 StartAuthProcess(serviceInfoProfile_.GetAuthType());
1740 return;
1741 }
1742 if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) {
1743 LOGI("start auth process");
1744 StartAuthProcess(authenticationType_);
1745 return;
1746 }
1747 LOGI("ShowConfigDialog start");
1748 JsonObject jsonObj;
1749 jsonObj[TAG_AUTH_TYPE] = AUTH_TYPE_PIN;
1750 jsonObj[TAG_TOKEN] = authResponseContext_->token;
1751 jsonObj[TARGET_PKG_NAME_KEY] = authResponseContext_->targetPkgName;
1752 jsonObj[TAG_CUSTOM_DESCRIPTION] = authResponseContext_->customDesc;
1753 jsonObj[TAG_APP_OPERATION] = authResponseContext_->appOperation;
1754 jsonObj[TAG_LOCAL_DEVICE_TYPE] = authResponseContext_->deviceTypeId;
1755 jsonObj[TAG_REQUESTER] = authResponseContext_->deviceName;
1756 jsonObj[TAG_HOST_PKGLABEL] = authResponseContext_->hostPkgLabel;
1757 const std::string params = SafetyDump(jsonObj);
1758 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
1759 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
1760 std::string localUdid = static_cast<std::string>(localDeviceId);
1761 DeviceProfileConnector::GetInstance().SyncAclByBindType(authResponseContext_->peerBundleName,
1762 authResponseContext_->bindType, localUdid, remoteDeviceId_);
1763 DmDialogManager::GetInstance().ShowConfirmDialog(params);
1764 struct RadarInfo info = {
1765 .funcName = "ShowConfigDialog",
1766 .stageRes = static_cast<int32_t>(StageRes::STAGE_IDLE),
1767 };
1768 if (!DmRadarHelper::GetInstance().ReportAuthPullAuthBox(info)) {
1769 LOGE("ReportAuthPullAuthBox failed");
1770 }
1771 LOGI("ShowConfigDialog end");
1772 }
1773
ShowAuthInfoDialog(bool authDeviceError)1774 void DmAuthManager::ShowAuthInfoDialog(bool authDeviceError)
1775 {
1776 if (authResponseContext_ == nullptr) {
1777 LOGE("failed to ShowAuthInfoDialog because authResponseContext_ is nullptr");
1778 return;
1779 }
1780 LOGI("DmAuthManager::ShowAuthInfoDialog start");
1781 if (!authDeviceError && CanUsePincodeFromDp()) {
1782 LOGI("pin import from dp, not show dialog");
1783 return;
1784 }
1785 if (pincodeDialogEverShown_) {
1786 return;
1787 }
1788 if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) {
1789 LOGI("not show dialog.");
1790 return;
1791 }
1792 struct RadarInfo info = {
1793 .funcName = "ShowAuthInfoDialog",
1794 .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
1795 };
1796 if (!DmRadarHelper::GetInstance().ReportAuthPullPinBox(info)) {
1797 LOGE("ReportAuthPullPinBox failed");
1798 }
1799 JsonObject jsonObj;
1800 jsonObj[PIN_CODE_KEY] = authResponseContext_->code;
1801 std::string authParam = SafetyDump(jsonObj);
1802 pincodeDialogEverShown_ = true;
1803 DmDialogManager::GetInstance().ShowPinDialog(std::to_string(authResponseContext_->code));
1804 }
1805
ShowStartAuthDialog()1806 void DmAuthManager::ShowStartAuthDialog()
1807 {
1808 if (authResponseContext_ == nullptr) {
1809 LOGE("failed to ShowStartAuthDialog because authResponseContext_ is nullptr");
1810 return;
1811 }
1812 if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
1813 LOGI("Add member start");
1814 int32_t pinCode = -1;
1815 if (GetAuthCode(authResponseContext_->hostPkgName, pinCode) != DM_OK) {
1816 LOGE("failed to get auth code");
1817 return;
1818 }
1819 if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1820 (static_cast<uint32_t>(authResponseContext_->bindLevel) >= DEVICE &&
1821 static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
1822 AuthDevice(pinCode);
1823 } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
1824 authResponseContext_->bindLevel == INVALIED_TYPE) {
1825 AddMember(pinCode);
1826 } else {
1827 LOGE("Invalied bind mode.");
1828 }
1829 return;
1830 }
1831 if (IsScreenLocked()) {
1832 LOGE("ShowStartAuthDialog screen is locked.");
1833 SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT);
1834 return;
1835 }
1836 LOGI("DmAuthManager::ShowStartAuthDialog start");
1837 int32_t pincode = 0;
1838 if (authResponseContext_->authType == AUTH_TYPE_NFC &&
1839 GetAuthCode(authResponseContext_->hostPkgName, pincode) == DM_OK) {
1840 LOGI("already has pin code");
1841 ProcessPincode(pincode);
1842 return;
1843 }
1844
1845 pincodeDialogEverShown_ = true;
1846 DmDialogManager::GetInstance().ShowInputDialog(authResponseContext_->targetDeviceName);
1847 }
1848
ProcessPincode(int32_t pinCode)1849 int32_t DmAuthManager::ProcessPincode(int32_t pinCode)
1850 {
1851 if (authResponseContext_ == nullptr) {
1852 LOGE("failed to ProcessPincode because authResponseContext_ is nullptr");
1853 return ERR_DM_FAILED;
1854 }
1855 if (timer_ != nullptr) {
1856 timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK));
1857 }
1858 if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) &&
1859 (static_cast<uint32_t>(authResponseContext_->bindLevel) >= DEVICE &&
1860 static_cast<uint32_t>(authResponseContext_->bindLevel) <= APP)) {
1861 return AuthDevice(pinCode);
1862 } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) ||
1863 authResponseContext_->bindLevel == INVALIED_TYPE) {
1864 return AddMember(pinCode);
1865 } else {
1866 LOGE("Invalied bind mode.");
1867 }
1868 return ERR_DM_FAILED;
1869 }
1870
AuthDevice(int32_t pinCode)1871 int32_t DmAuthManager::AuthDevice(int32_t pinCode)
1872 {
1873 LOGI("DmAuthManager::AuthDevice start.");
1874 if (isAuthDevice_) {
1875 LOGE("DmAuthManager::AuthDevice doing auth device.");
1876 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_DOING_AUTH);
1877 return ERR_DM_FAILED;
1878 }
1879 isAuthDevice_ = true;
1880 int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();
1881 if (timer_ != nullptr) {
1882 timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK));
1883 timer_->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), AUTH_DEVICE_TIMEOUT,
1884 [this] (std::string name) {
1885 DmAuthManager::HandleAuthenticateTimeout(name);
1886 });
1887 }
1888 if (hiChainAuthConnector_->AuthDevice(pinCode, osAccountId, remoteDeviceId_,
1889 authResponseContext_->requestId) != DM_OK) {
1890 LOGE("DmAuthManager::AuthDevice failed.");
1891 isAuthDevice_ = false;
1892 if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
1893 HandleMemberJoinImportAuthCode(authResponseContext_->requestId, ERR_DM_FAILED);
1894 return ERR_DM_FAILED;
1895 }
1896 }
1897 return DM_OK;
1898 }
1899
OnUserOperation(int32_t action,const std::string & params)1900 int32_t DmAuthManager::OnUserOperation(int32_t action, const std::string ¶ms)
1901 {
1902 if (authResponseContext_ == nullptr) {
1903 LOGE("Authenticate is not start");
1904 return ERR_DM_AUTH_NOT_START;
1905 }
1906 struct RadarInfo info = {
1907 .funcName = "OnUserOperation",
1908 .stageRes = static_cast<int32_t>(StageRes::STAGE_CANCEL),
1909 .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
1910 };
1911 switch (action) {
1912 case USER_OPERATION_TYPE_ALLOW_AUTH:
1913 case USER_OPERATION_TYPE_CANCEL_AUTH:
1914 case USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS:
1915 StartAuthProcess(action);
1916 break;
1917 case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT:
1918 SetReasonAndFinish(ERR_DM_TIME_OUT, STATUS_DM_AUTH_DEFAULT);
1919 info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_TIME_OUT);
1920 if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) {
1921 LOGE("ReportAuthConfirmBox failed");
1922 }
1923 break;
1924 case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY:
1925 SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY, STATUS_DM_AUTH_DEFAULT);
1926 info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY);
1927 if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) {
1928 LOGE("ReportAuthInputPinBox failed");
1929 }
1930 break;
1931 case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT:
1932 SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_ERROR, STATUS_DM_AUTH_DEFAULT);
1933 info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_ERROR);
1934 if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) {
1935 LOGE("ReportAuthInputPinBox failed");
1936 }
1937 break;
1938 case USER_OPERATION_TYPE_DONE_PINCODE_INPUT:
1939 ProcessPincode(std::atoi(params.c_str()));
1940 info.stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC);
1941 if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) {
1942 LOGE("ReportAuthInputPinBox failed");
1943 }
1944 break;
1945 default:
1946 LOGE("this action id not support");
1947 break;
1948 }
1949 return DM_OK;
1950 }
1951
SetPageId(int32_t pageId)1952 int32_t DmAuthManager::SetPageId(int32_t pageId)
1953 {
1954 if (authResponseContext_ == nullptr) {
1955 LOGE("Authenticate is not start");
1956 return ERR_DM_AUTH_NOT_START;
1957 }
1958 authResponseContext_->pageId = pageId;
1959 return DM_OK;
1960 }
1961
SetReasonAndFinish(int32_t reason,int32_t state)1962 int32_t DmAuthManager::SetReasonAndFinish(int32_t reason, int32_t state)
1963 {
1964 if (authResponseContext_ == nullptr) {
1965 LOGE("Authenticate is not start");
1966 return ERR_DM_AUTH_NOT_START;
1967 }
1968 authResponseContext_->state = state;
1969 authResponseContext_->reply = reason;
1970 if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_FINISH) {
1971 authRequestContext_->reason = reason;
1972 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
1973 } else if (authResponseState_ != nullptr && authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_FINISH) {
1974 authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
1975 }
1976 return DM_OK;
1977 }
1978
IsIdenticalAccount()1979 bool DmAuthManager::IsIdenticalAccount()
1980 {
1981 JsonObject jsonObj;
1982 jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP;
1983 std::string queryParams = SafetyDump(jsonObj);
1984
1985 int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID();
1986 if (osAccountUserId < 0) {
1987 LOGE("get current process account user id failed");
1988 return false;
1989 }
1990 std::vector<GroupInfo> groupList;
1991 if (!hiChainConnector_->GetGroupInfo(osAccountUserId, queryParams, groupList)) {
1992 return false;
1993 }
1994 if (authResponseContext_ == nullptr) {
1995 LOGE("authResponseContext_ is nullptr.");
1996 return false;
1997 }
1998 if (authResponseContext_->accountGroupIdHash == OLD_VERSION_ACCOUNT) {
1999 LOGI("The old version.");
2000 return true;
2001 }
2002 JsonObject jsonPeerGroupIdObj(authResponseContext_->accountGroupIdHash);
2003 if (jsonPeerGroupIdObj.IsDiscarded()) {
2004 LOGE("accountGroupIdHash string not a json type.");
2005 return false;
2006 }
2007
2008 std::vector<JsonItemObject> items = jsonPeerGroupIdObj.Items();
2009 for (auto &groupInfo : groupList) {
2010 for (auto it = items.begin(); it != items.end(); ++it) {
2011 if (it->IsString() && it->Get<std::string>() == Crypto::GetGroupIdHash(groupInfo.groupId)) {
2012 LOGI("Is identical Account.");
2013 return true;
2014 }
2015 }
2016 }
2017 return false;
2018 }
2019
GetAccountGroupIdHash()2020 std::string DmAuthManager::GetAccountGroupIdHash()
2021 {
2022 JsonObject jsonObj;
2023 jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP;
2024 std::string queryParams = SafetyDump(jsonObj);
2025
2026 int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID();
2027 if (osAccountUserId < 0) {
2028 LOGE("get current process account user id failed");
2029 return "";
2030 }
2031 std::vector<GroupInfo> groupList;
2032 if (!hiChainConnector_->GetGroupInfo(osAccountUserId, queryParams, groupList)) {
2033 return "";
2034 }
2035 JsonObject jsonAccountObj(JsonCreateType::JSON_CREATE_TYPE_ARRAY);
2036 for (auto &groupInfo : groupList) {
2037 jsonAccountObj.PushBack(Crypto::GetGroupIdHash(groupInfo.groupId));
2038 }
2039 return SafetyDump(jsonAccountObj);
2040 }
2041
ImportAuthCode(const std::string & pkgName,const std::string & authCode)2042 int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode)
2043 {
2044 if (authCode.empty() || pkgName.empty()) {
2045 LOGE("ImportAuthCode failed, authCode or pkgName is empty");
2046 return ERR_DM_INPUT_PARA_INVALID;
2047 }
2048 importAuthCode_ = authCode;
2049 importPkgName_ = pkgName;
2050 return DM_OK;
2051 }
2052
BindTarget(const std::string & pkgName,const PeerTargetId & targetId,const std::map<std::string,std::string> & bindParam)2053 int32_t DmAuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId,
2054 const std::map<std::string, std::string> &bindParam)
2055 {
2056 struct RadarInfo info = {
2057 .funcName = "AuthenticateDevice",
2058 .stageRes = static_cast<int32_t>(StageRes::STAGE_SUCC),
2059 .bizState = static_cast<int32_t>(BizState::BIZ_STATE_END),
2060 };
2061 if (!DmRadarHelper::GetInstance().ReportDiscoverUserRes(info)) {
2062 LOGE("ReportDiscoverUserRes failed");
2063 }
2064 if (pkgName.empty()) {
2065 LOGE("DmAuthManager::BindTarget failed, pkgName is empty.");
2066 return ERR_DM_INPUT_PARA_INVALID;
2067 }
2068 int32_t authType = -1;
2069 if (ParseAuthType(bindParam, authType) != DM_OK) {
2070 LOGE("DmAuthManager::BindTarget failed, key: %{public}s error.", PARAM_KEY_AUTH_TYPE);
2071 return ERR_DM_INPUT_PARA_INVALID;
2072 }
2073 peerTargetId_ = targetId;
2074 std::string deviceId = "";
2075 std::string addrType;
2076 if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) {
2077 addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE);
2078 }
2079 if (ParseConnectAddr(targetId, deviceId, addrType) == DM_OK) {
2080 return AuthenticateDevice(pkgName, authType, deviceId, ParseExtraFromMap(bindParam));
2081 } else if (!targetId.deviceId.empty()) {
2082 return AuthenticateDevice(pkgName, authType, targetId.deviceId, ParseExtraFromMap(bindParam));
2083 } else {
2084 LOGE("DmAuthManager::BindTarget failed, targetId is error.");
2085 return ERR_DM_INPUT_PARA_INVALID;
2086 }
2087 }
2088
ParseConnectAddr(const PeerTargetId & targetId,std::string & deviceId,std::string & addrType)2089 int32_t DmAuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType)
2090 {
2091 int32_t index = 0;
2092 std::shared_ptr<DeviceInfo> deviceInfo = std::make_shared<DeviceInfo>();
2093 ConnectionAddr addr;
2094 if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) {
2095 LOGI("DmAuthManager::ParseConnectAddr parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str());
2096 if (!addrType.empty()) {
2097 addr.type = static_cast<ConnectionAddrType>(std::atoi(addrType.c_str()));
2098 } else {
2099 addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN;
2100 }
2101 memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length());
2102 addr.info.ip.port = targetId.wifiPort;
2103 deviceInfo->addr[index] = addr;
2104 deviceId = targetId.wifiIp;
2105 index++;
2106 } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) {
2107 LOGI("DmAuthManager::ParseConnectAddr parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str());
2108 addr.type = ConnectionAddrType::CONNECTION_ADDR_BR;
2109 memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length());
2110 deviceInfo->addr[index] = addr;
2111 deviceId = targetId.brMac;
2112 index++;
2113 } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) {
2114 LOGI("DmAuthManager::ParseConnectAddr parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str());
2115 addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE;
2116 memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length());
2117 if (!targetId.deviceId.empty()) {
2118 Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN,
2119 targetId.deviceId.c_str(), targetId.deviceId.length());
2120 }
2121 deviceInfo->addr[index] = addr;
2122 deviceId = targetId.bleMac;
2123 index++;
2124 } else {
2125 LOGE("DmAuthManager::ParseConnectAddr failed, not addr.");
2126 return ERR_DM_INPUT_PARA_INVALID;
2127 }
2128
2129 deviceInfo->addrNum = static_cast<uint32_t>(index);
2130 if (softbusConnector_->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) {
2131 LOGE("DmAuthManager::ParseConnectAddr failed, AddMemberToDiscoverMap failed.");
2132 return ERR_DM_INPUT_PARA_INVALID;
2133 }
2134 deviceInfo = nullptr;
2135 return DM_OK;
2136 }
2137
ParseAuthType(const std::map<std::string,std::string> & bindParam,int32_t & authType)2138 int32_t DmAuthManager::ParseAuthType(const std::map<std::string, std::string> &bindParam, int32_t &authType)
2139 {
2140 auto iter = bindParam.find(PARAM_KEY_AUTH_TYPE);
2141 if (iter == bindParam.end()) {
2142 LOGE("DmAuthManager::ParseAuthType bind param key: %{public}s not exist.", PARAM_KEY_AUTH_TYPE);
2143 return ERR_DM_INPUT_PARA_INVALID;
2144 }
2145 std::string authTypeStr = iter->second;
2146 if (authTypeStr.empty()) {
2147 LOGE("DmAuthManager::ParseAuthType bind param %{public}s is empty.", PARAM_KEY_AUTH_TYPE);
2148 return ERR_DM_INPUT_PARA_INVALID;
2149 }
2150 if (authTypeStr.length() > 1) {
2151 LOGE("DmAuthManager::ParseAuthType bind param %{public}s length is unsupported.", PARAM_KEY_AUTH_TYPE);
2152 return ERR_DM_INPUT_PARA_INVALID;
2153 }
2154 if (!isdigit(authTypeStr[0])) {
2155 LOGE("DmAuthManager::ParseAuthType bind param %{public}s fromat is unsupported.", PARAM_KEY_AUTH_TYPE);
2156 return ERR_DM_INPUT_PARA_INVALID;
2157 }
2158 authType = std::atoi(authTypeStr.c_str());
2159 return DM_OK;
2160 }
2161
ParseExtraFromMap(const std::map<std::string,std::string> & bindParam)2162 std::string DmAuthManager::ParseExtraFromMap(const std::map<std::string, std::string> &bindParam)
2163 {
2164 auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA);
2165 if (iter != bindParam.end()) {
2166 return iter->second;
2167 }
2168 return ConvertMapToJsonString(bindParam);
2169 }
2170
IsAuthCodeReady(const std::string & pkgName)2171 bool DmAuthManager::IsAuthCodeReady(const std::string &pkgName)
2172 {
2173 if (importAuthCode_.empty() || importPkgName_.empty()) {
2174 LOGE("DmAuthManager::IsAuthCodeReady, auth code not ready.");
2175 return false;
2176 }
2177 if (pkgName != importPkgName_) {
2178 LOGE("IsAuthCodeReady failed, pkgName not supported.");
2179 return false;
2180 }
2181 return true;
2182 }
2183
DeleteAuthCode()2184 int32_t DmAuthManager::DeleteAuthCode()
2185 {
2186 importAuthCode_ = "";
2187 importPkgName_ = "";
2188 return DM_OK;
2189 }
2190
GetAuthCode(const std::string & pkgName,int32_t & pinCode)2191 int32_t DmAuthManager::GetAuthCode(const std::string &pkgName, int32_t &pinCode)
2192 {
2193 if (importAuthCode_.empty() || importPkgName_.empty()) {
2194 LOGE("GetAuthCode failed, auth code not exist.");
2195 return ERR_DM_FAILED;
2196 }
2197 if (pkgName != importPkgName_) {
2198 LOGE("GetAuthCode failed, pkgName not supported.");
2199 return ERR_DM_FAILED;
2200 }
2201 pinCode = std::atoi(importAuthCode_.c_str());
2202 return DM_OK;
2203 }
2204
IsImportedAuthCodeValid()2205 bool DmAuthManager::IsImportedAuthCodeValid()
2206 {
2207 int32_t pinCode = 0;
2208 if (GetAuthCode(authRequestContext_->hostPkgName, pinCode) == DM_OK) {
2209 return true;
2210 }
2211 return false;
2212 }
2213
IsSrc()2214 bool DmAuthManager::IsSrc()
2215 {
2216 if (authRequestState_ != nullptr) {
2217 return true;
2218 } else {
2219 return false;
2220 }
2221 }
2222
IsAuthTypeSupported(const int32_t & authType)2223 bool DmAuthManager::IsAuthTypeSupported(const int32_t &authType)
2224 {
2225 if (authenticationMap_.find(authType) == authenticationMap_.end()) {
2226 LOGE("IsAuthTypeSupported failed, authType is not supported.");
2227 return false;
2228 }
2229 return true;
2230 }
2231
GenerateBindResultContent()2232 std::string DmAuthManager::GenerateBindResultContent()
2233 {
2234 JsonObject jsonObj;
2235 jsonObj[DM_BIND_RESULT_NETWORK_ID] = authResponseContext_->networkId;
2236 if (remoteDeviceId_.empty()) {
2237 jsonObj[TAG_DEVICE_ID] = "";
2238 } else {
2239 char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0};
2240 Crypto::GetUdidHash(remoteDeviceId_, reinterpret_cast<uint8_t *>(deviceIdHash));
2241 jsonObj[TAG_DEVICE_ID] = deviceIdHash;
2242 }
2243 std::string content = SafetyDump(jsonObj);
2244 return content;
2245 }
2246
RequestCredential()2247 void DmAuthManager::RequestCredential()
2248 {
2249 LOGI("DmAuthManager::RequestCredential start.");
2250 std::string publicKey = "";
2251 GenerateCredential(publicKey);
2252 authResponseContext_->publicKey = publicKey;
2253 std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_PUBLICKEY);
2254 softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
2255 }
2256
GenerateCredential(std::string & publicKey)2257 void DmAuthManager::GenerateCredential(std::string &publicKey)
2258 {
2259 LOGI("DmAuthManager::GenerateCredential start.");
2260 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2261 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2262 std::string localUdid = localDeviceId;
2263 int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();
2264 hiChainAuthConnector_->GetCredential(localUdid, osAccountId, publicKey);
2265 if (publicKey == "") {
2266 hiChainAuthConnector_->GenerateCredential(localUdid, osAccountId, publicKey);
2267 }
2268 }
2269
RequestCredentialDone()2270 void DmAuthManager::RequestCredentialDone()
2271 {
2272 LOGI("DmAuthManager ExchangeCredentailDone start");
2273 CHECK_NULL_VOID(authResponseContext_);
2274 if (authResponseContext_->publicKey == "" ||
2275 ImportCredential(remoteDeviceId_, authResponseContext_->publicKey) != DM_OK) {
2276 LOGE("RequestCredentialDone import credential failed.");
2277 }
2278 if (timer_ != nullptr) {
2279 timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK));
2280 }
2281 if (softbusConnector_->CheckIsOnline(remoteDeviceId_) && !authResponseContext_->isOnline) {
2282 JoinLnn(authRequestContext_->addr, true);
2283 } else {
2284 JoinLnn(authRequestContext_->addr, false);
2285 }
2286 authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
2287 authRequestContext_->reason = DM_OK;
2288 authResponseContext_->reply = DM_OK;
2289 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2290 }
2291
ImportCredential(std::string & deviceId,std::string & publicKey)2292 int32_t DmAuthManager::ImportCredential(std::string &deviceId, std::string &publicKey)
2293 {
2294 LOGI("DmAuthManager::ImportCredential");
2295 int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();
2296 return hiChainAuthConnector_->ImportCredential(osAccountId, deviceId, publicKey);
2297 }
2298
ResponseCredential()2299 void DmAuthManager::ResponseCredential()
2300 {
2301 LOGI("DmAuthManager::ResponseCredential start.");
2302 CHECK_NULL_VOID(authResponseContext_);
2303 if (authResponseContext_->publicKey == "") {
2304 LOGE("authResponseContext_->publicKey is empty.");
2305 authResponseContext_->isFinish = false;
2306 isFinishOfLocal_ = false;
2307 authMessageProcessor_->SetEncryptFlag(false);
2308 authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
2309 return;
2310 }
2311 std::string publicKey = "";
2312 GenerateCredential(publicKey);
2313 if (ImportCredential(remoteDeviceId_, authResponseContext_->publicKey) != DM_OK) {
2314 LOGE("ResponseCredential import credential failed.");
2315 authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
2316 return;
2317 }
2318 authResponseContext_->publicKey = publicKey;
2319 std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_PUBLICKEY);
2320 softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
2321 }
2322
AuthDeviceTransmit(int64_t requestId,const uint8_t * data,uint32_t dataLen)2323 bool DmAuthManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen)
2324 {
2325 LOGI("DmAuthManager::onTransmit start.");
2326 if (requestId != authResponseContext_->requestId) {
2327 LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64"is error.", requestId);
2328 return false;
2329 }
2330 std::string message = "";
2331 if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2332 LOGI("SoftbusSession send msgType %{public}d.", MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE);
2333 message = authMessageProcessor_->CreateDeviceAuthMessage(MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE, data, dataLen);
2334 } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2335 LOGI("SoftbusSession send msgType %{public}d.", MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE);
2336 message = authMessageProcessor_->CreateDeviceAuthMessage(MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE, data, dataLen);
2337 }
2338 if (softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message) != DM_OK) {
2339 LOGE("SoftbusSession send data failed.");
2340 return false;
2341 }
2342 return true;
2343 }
2344
SrcAuthDeviceFinish()2345 void DmAuthManager::SrcAuthDeviceFinish()
2346 {
2347 LOGI("DmAuthManager::SrcAuthDeviceFinish Start.");
2348 CHECK_NULL_VOID(authRequestState_);
2349 authRequestState_->TransitionTo(std::make_shared<AuthRequestAuthFinish>());
2350 if (authResponseContext_->confirmOperation != USER_OPERATION_TYPE_ALLOW_AUTH &&
2351 authResponseContext_->confirmOperation != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
2352 LOGE("auth failed %{public}d.", authResponseContext_->confirmOperation);
2353 return;
2354 }
2355 if (authResponseContext_->isOnline && authResponseContext_->haveCredential) {
2356 if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) {
2357 SetProcessInfo();
2358 }
2359 softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_);
2360 if (timer_ != nullptr) {
2361 timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK));
2362 }
2363 ConverToFinish();
2364 return;
2365 }
2366 if (authResponseContext_->isOnline && !authResponseContext_->haveCredential) {
2367 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT);
2368 if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) {
2369 SetProcessInfo();
2370 }
2371 softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_);
2372 if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) {
2373 authRequestState_->TransitionTo(std::make_shared<AuthRequestReCheckMsg>());
2374 } else {
2375 authRequestState_->TransitionTo(std::make_shared<AuthRequestCredential>());
2376 }
2377 return;
2378 }
2379 if (!authResponseContext_->isOnline && authResponseContext_->haveCredential) {
2380 JoinLnn(authRequestContext_->addr);
2381 timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK));
2382 ConverToFinish();
2383 return;
2384 }
2385 if (!authResponseContext_->isOnline && !authResponseContext_->haveCredential) {
2386 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT);
2387 if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) {
2388 authRequestState_->TransitionTo(std::make_shared<AuthRequestReCheckMsg>());
2389 } else {
2390 authRequestState_->TransitionTo(std::make_shared<AuthRequestCredential>());
2391 }
2392 return;
2393 }
2394 }
2395
SinkAuthDeviceFinish()2396 void DmAuthManager::SinkAuthDeviceFinish()
2397 {
2398 LOGI("isNeedProcCachedSrcReqMsg %{public}d.", isNeedProcCachedSrcReqMsg_);
2399 CHECK_NULL_VOID(authResponseState_);
2400 authResponseState_->TransitionTo(std::make_shared<AuthResponseAuthFinish>());
2401 if (!authResponseContext_->haveCredential) {
2402 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW);
2403 }
2404 if (authResponseContext_->isOnline) {
2405 LOGI("The device is online.");
2406 SetProcessInfo();
2407 softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_);
2408 }
2409 std::string srcReqMsg = "";
2410 bool isNeedProcCachedSrcReqMsg = false;
2411 {
2412 std::lock_guard<std::mutex> lock(srcReqMsgLock_);
2413 srcReqMsg = srcReqMsg_;
2414 isNeedProcCachedSrcReqMsg = isNeedProcCachedSrcReqMsg_;
2415 srcReqMsg_ = "";
2416 isNeedProcCachedSrcReqMsg_ = false;
2417 }
2418 if (!isNeedProcCachedSrcReqMsg || srcReqMsg.empty()) {
2419 LOGI("please wait client request.");
2420 return;
2421 }
2422 authMessageProcessor_->SetResponseContext(authResponseContext_);
2423 if (authMessageProcessor_->ParseMessage(srcReqMsg) != DM_OK) {
2424 LOGE("ParseMessage failed.");
2425 return;
2426 }
2427 if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) {
2428 authResponseState_->TransitionTo(std::make_shared<AuthResponseCredential>());
2429 } else {
2430 authResponseState_->TransitionTo(std::make_shared<AuthResponseReCheckMsg>());
2431 }
2432 }
2433
AuthDeviceFinish(int64_t requestId)2434 void DmAuthManager::AuthDeviceFinish(int64_t requestId)
2435 {
2436 LOGI("DmAuthManager::AuthDeviceFinish start.");
2437 if (requestId != authResponseContext_->requestId) {
2438 LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64 "is error.", requestId);
2439 return;
2440 }
2441 isAuthDevice_ = false;
2442 if (timer_ != nullptr) {
2443 timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK));
2444 }
2445 if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_2))) {
2446 LOGI("Set EncryptFlag true.");
2447 authMessageProcessor_->SetEncryptFlag(true);
2448 } else {
2449 PutAccessControlList();
2450 }
2451 if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2452 SrcAuthDeviceFinish();
2453 } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2454 SinkAuthDeviceFinish();
2455 }
2456 }
2457
AuthDeviceError(int64_t requestId,int32_t errorCode)2458 void DmAuthManager::AuthDeviceError(int64_t requestId, int32_t errorCode)
2459 {
2460 LOGI("AuthDeviceError start.");
2461 isAuthDevice_ = false;
2462 if (authRequestState_ == nullptr || authResponseState_ != nullptr) {
2463 if (CheckNeedShowAuthInfoDialog(errorCode)) {
2464 return;
2465 }
2466 authTimes_++;
2467 if (authTimes_ >= MAX_AUTH_TIMES) {
2468 authResponseContext_->isFinish = false;
2469 authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT;
2470 authResponseContext_->state = AuthState::AUTH_RESPONSE_SHOW;
2471 isFinishOfLocal_ = false;
2472 authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
2473 }
2474 return;
2475 }
2476 if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
2477 if (requestId != authResponseContext_->requestId) {
2478 LOGE("DmAuthManager::AuthDeviceError requestId %{public}" PRId64 "is error.", requestId);
2479 return;
2480 }
2481 authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN;
2482 authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT;
2483 authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT;
2484 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2485 return;
2486 }
2487 authTimes_++;
2488 if (timer_ != nullptr) {
2489 timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK));
2490 }
2491 if (errorCode != DM_OK || requestId != authResponseContext_->requestId) {
2492 if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) {
2493 authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN;
2494 authRequestContext_->reason = ERR_DM_INPUT_PARA_INVALID;
2495 authResponseContext_->reply = ERR_DM_INPUT_PARA_INVALID;
2496 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2497 } else {
2498 if (timer_ != nullptr) {
2499 timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK),
2500 GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) {
2501 DmAuthManager::HandleAuthenticateTimeout(name);
2502 });
2503 }
2504 UpdateInputPincodeDialog(errorCode);
2505 }
2506 }
2507 }
2508
AuthDeviceSessionKey(int64_t requestId,const uint8_t * sessionKey,uint32_t sessionKeyLen)2509 void DmAuthManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen)
2510 {
2511 LOGI("DmAuthManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen);
2512 if (requestId != authResponseContext_->requestId) {
2513 LOGE("DmAuthManager::onTransmit requestId %{public}" PRId64 "is error.", requestId);
2514 return;
2515 }
2516 CHECK_NULL_VOID(authMessageProcessor_);
2517 if (CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_4))) {
2518 if (authMessageProcessor_->ProcessSessionKey(sessionKey, sessionKeyLen) != DM_OK) {
2519 LOGE("Process session key err.");
2520 return;
2521 }
2522 } else {
2523 if (authMessageProcessor_->SaveSessionKey(sessionKey, sessionKeyLen) != DM_OK) {
2524 LOGE("Save session key err.");
2525 return;
2526 }
2527 }
2528 authResponseContext_->localSessionKeyId = 0;
2529 {
2530 std::lock_guard<std::mutex> guard(sessionKeyIdMutex_);
2531 sessionKeyIdAsyncResult_.clear();
2532 sessionKeyIdAsyncResult_[requestId] = std::optional<int32_t>();
2533 }
2534 unsigned char hash[SHA256_DIGEST_LENGTH] = { 0 };
2535 Crypto::DmGenerateStrHash(sessionKey, sessionKeyLen, hash, SHA256_DIGEST_LENGTH, 0);
2536 std::vector<unsigned char> hashVector(hash, hash + SHA256_DIGEST_LENGTH);
2537 std::shared_ptr<DmAuthManager> sharePtrThis = shared_from_this();
2538 auto asyncTaskFunc = [sharePtrThis, requestId, hashVector]() {
2539 sharePtrThis->PutSessionKeyAsync(requestId, hashVector);
2540 };
2541 ffrt::submit(asyncTaskFunc, ffrt::task_attr().delay(0));
2542 }
2543
PutSessionKeyAsync(int64_t requestId,std::vector<unsigned char> hash)2544 void DmAuthManager::PutSessionKeyAsync(int64_t requestId, std::vector<unsigned char> hash)
2545 {
2546 {
2547 std::lock_guard<std::mutex> guard(sessionKeyIdMutex_);
2548 int32_t sessionKeyId = 0;
2549 int32_t ret = DeviceProfileConnector::GetInstance().PutSessionKey(hash, sessionKeyId);
2550 if (ret != DM_OK) {
2551 LOGI("PutSessionKey failed.");
2552 sessionKeyId = 0;
2553 }
2554 sessionKeyIdAsyncResult_[requestId] = sessionKeyId;
2555 }
2556 sessionKeyIdCondition_.notify_one();
2557 }
2558
GetSessionKeyIdSync(int64_t requestId)2559 int32_t DmAuthManager::GetSessionKeyIdSync(int64_t requestId)
2560 {
2561 std::unique_lock<std::mutex> guard(sessionKeyIdMutex_);
2562 if (sessionKeyIdAsyncResult_.find(requestId) == sessionKeyIdAsyncResult_.end()) {
2563 LOGW("GetSessionKeyIdSync failed, not find by requestId");
2564 return 0;
2565 }
2566 if (sessionKeyIdAsyncResult_[requestId].has_value()) {
2567 LOGI("GetSessionKeyIdSync, already ready");
2568 return sessionKeyIdAsyncResult_[requestId].value();
2569 }
2570 LOGI("GetSessionKeyIdSync need wait");
2571 sessionKeyIdCondition_.wait_for(guard, std::chrono::milliseconds(MAX_PUT_SESSIONKEY_TIMEOUT));
2572 int32_t keyid = sessionKeyIdAsyncResult_[requestId].value_or(0);
2573 LOGI("GetSessionKeyIdSync exit");
2574 return keyid;
2575 }
2576
GetRemoteDeviceId(std::string & deviceId)2577 void DmAuthManager::GetRemoteDeviceId(std::string &deviceId)
2578 {
2579 LOGI("GetRemoteDeviceId start.");
2580 deviceId = remoteDeviceId_;
2581 }
2582
CompatiblePutAcl()2583 void DmAuthManager::CompatiblePutAcl()
2584 {
2585 LOGI("DmAuthManager::CompatiblePutAcl");
2586 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2587 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2588 std::string localUdid = static_cast<std::string>(localDeviceId);
2589 char mUdidHash[DM_MAX_DEVICE_ID_LEN] = {0};
2590 Crypto::GetUdidHash(localUdid, reinterpret_cast<uint8_t *>(mUdidHash));
2591 std::string localUdidHash = static_cast<std::string>(mUdidHash);
2592 DmAclInfo aclInfo;
2593 aclInfo.bindLevel = DEVICE;
2594 aclInfo.bindType = DM_POINT_TO_POINT;
2595 aclInfo.trustDeviceId = remoteDeviceId_;
2596 if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
2597 aclInfo.authenticationType = ALLOW_AUTH_ALWAYS;
2598 } else if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH) {
2599 aclInfo.authenticationType = ALLOW_AUTH_ONCE;
2600 }
2601 aclInfo.deviceIdHash = localUdidHash;
2602
2603 DmAccesser accesser;
2604 DmAccessee accessee;
2605 if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2606 accesser.requestBundleName = authResponseContext_->hostPkgName;
2607 accesser.requestDeviceId = localUdid;
2608 accesser.requestUserId = MultipleUserConnector::GetCurrentAccountUserID();
2609 accesser.requestAccountId = MultipleUserConnector::GetAccountInfoByUserId(accesser.requestUserId).accountId;
2610 accesser.requestTokenId = static_cast<uint64_t>(authRequestContext_->tokenId);
2611 accessee.trustBundleName = authResponseContext_->hostPkgName;
2612 accessee.trustDeviceId = remoteDeviceId_;
2613 accessee.trustUserId = -1;
2614 }
2615 if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2616 accesser.requestBundleName = authResponseContext_->hostPkgName;
2617 accesser.requestDeviceId = remoteDeviceId_;
2618 accesser.requestUserId = authResponseContext_->remoteUserId;
2619 accesser.requestAccountId = authResponseContext_->remoteAccountId;
2620 accesser.requestTokenId = static_cast<uint64_t>(authResponseContext_->remoteTokenId);
2621 accessee.trustBundleName = authResponseContext_->hostPkgName;
2622 accessee.trustDeviceId = localUdid;
2623 accessee.trustUserId = MultipleUserConnector::GetCurrentAccountUserID();
2624 accessee.trustAccountId = MultipleUserConnector::GetAccountInfoByUserId(accessee.trustUserId).accountId;
2625 accessee.trustTokenId = static_cast<uint64_t>(authResponseContext_->tokenId);
2626 }
2627 DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, accesser, accessee);
2628 }
2629
ProcRespNegotiateExt(const int32_t & sessionId)2630 void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId)
2631 {
2632 LOGI("DmAuthManager::ProcRespNegotiateExt start.");
2633 remoteDeviceId_ = authResponseContext_->localDeviceId;
2634 authResponseContext_->remoteAccountId = authResponseContext_->localAccountId;
2635 authResponseContext_->remoteUserId = authResponseContext_->localUserId;
2636 GetBinderInfo();
2637 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2638 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2639 authResponseContext_->deviceId = authResponseContext_->localDeviceId;
2640 authResponseContext_->localDeviceId = static_cast<std::string>(localDeviceId);
2641 authResponseContext_->bindType =
2642 DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(authResponseContext_->hostPkgName,
2643 authResponseContext_->localDeviceId, authResponseContext_->deviceId);
2644 authResponseContext_->authed = !authResponseContext_->bindType.empty();
2645 if (authResponseContext_->authed && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
2646 !importAuthCode_.empty() && !CompareVersion(remoteVersion_, std::string(DM_VERSION_5_0_3))) {
2647 authResponseContext_->importAuthCode = Crypto::Sha256(importAuthCode_);
2648 }
2649
2650 authResponseContext_->isIdenticalAccount = false;
2651 if (authResponseContext_->localAccountId == authResponseContext_->remoteAccountId &&
2652 authResponseContext_->localAccountId != "ohosAnonymousUid" && authResponseContext_->authed) {
2653 authResponseContext_->isIdenticalAccount = true;
2654 }
2655
2656 authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_);
2657 authResponseContext_->haveCredential =
2658 hiChainAuthConnector_->QueryCredential(authResponseContext_->deviceId,
2659 MultipleUserConnector::GetFirstForegroundUserId());
2660 if (!IsAuthTypeSupported(authResponseContext_->authType)) {
2661 LOGE("DmAuthManager::AuthenticateDevice authType %{public}d not support.", authResponseContext_->authType);
2662 authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE;
2663 } else {
2664 authPtr_ = authenticationMap_[authResponseContext_->authType];
2665 }
2666 if (IsAuthCodeReady(authResponseContext_->hostPkgName)) {
2667 authResponseContext_->isAuthCodeReady = true;
2668 } else {
2669 authResponseContext_->isAuthCodeReady = false;
2670 }
2671 std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE);
2672 softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2673
2674 if (authResponseContext_->authType == AUTH_TYPE_NFC) {
2675 GetLocalServiceInfoInDp();
2676 }
2677 }
2678
ProcRespNegotiate(const int32_t & sessionId)2679 void DmAuthManager::ProcRespNegotiate(const int32_t &sessionId)
2680 {
2681 LOGI("DmAuthManager::ProcRespNegotiate session id");
2682 AbilityNegotiate();
2683 authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_);
2684 std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE);
2685 JsonObject jsonObject(message);
2686 if (jsonObject.IsDiscarded()) {
2687 softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2688 return;
2689 }
2690 if (!IsBool(jsonObject, TAG_CRYPTO_SUPPORT)) {
2691 LOGE("err json string.");
2692 softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2693 return;
2694 }
2695 if (IsIdenticalAccount()) {
2696 jsonObject[TAG_IDENTICAL_ACCOUNT] = true;
2697 if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && !importAuthCode_.empty()) {
2698 jsonObject[TAG_IMPORT_AUTH_CODE] = Crypto::Sha256(importAuthCode_);
2699 }
2700 }
2701 jsonObject[TAG_ACCOUNT_GROUPID] = GetAccountGroupIdHash();
2702 authResponseContext_ = authResponseState_->GetAuthContext();
2703 if (jsonObject[TAG_CRYPTO_SUPPORT].Get<bool>() == true && authResponseContext_->cryptoSupport) {
2704 if (IsString(jsonObject, TAG_CRYPTO_NAME) && IsString(jsonObject, TAG_CRYPTO_VERSION)) {
2705 if (jsonObject[TAG_CRYPTO_NAME].Get<std::string>() == authResponseContext_->cryptoName &&
2706 jsonObject[TAG_CRYPTO_VERSION].Get<std::string>() == authResponseContext_->cryptoVer) {
2707 isCryptoSupport_ = true;
2708 softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2709 return;
2710 }
2711 }
2712 }
2713 jsonObject[TAG_CRYPTO_SUPPORT] = false;
2714 message = SafetyDump(jsonObject);
2715 softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2716 }
2717
ProcIncompatible(const int32_t & sessionId)2718 void DmAuthManager::ProcIncompatible(const int32_t &sessionId)
2719 {
2720 LOGI("DmAuthManager::ProcIncompatible sessionId %{public}d.", sessionId);
2721 JsonObject respNegotiateMsg;
2722 respNegotiateMsg[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE;
2723 respNegotiateMsg[TAG_VER] = DM_ITF_VER;
2724 respNegotiateMsg[TAG_MSG_TYPE] = MSG_TYPE_RESP_NEGOTIATE;
2725 std::string message = SafetyDump(respNegotiateMsg);
2726 softbusConnector_->GetSoftbusSession()->SendData(sessionId, message);
2727 }
2728
OnAuthDeviceDataReceived(const int32_t sessionId,const std::string message)2729 void DmAuthManager::OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message)
2730 {
2731 if (authResponseContext_ == nullptr || authMessageProcessor_ == nullptr || hiChainAuthConnector_ == nullptr ||
2732 authResponseContext_->sessionId != sessionId) {
2733 LOGE("OnAuthDeviceDataReceived param is invalid");
2734 return;
2735 }
2736 authResponseContext_->sessionId = sessionId;
2737 authMessageProcessor_->SetResponseContext(authResponseContext_);
2738 JsonObject jsonObject(message);
2739 if (jsonObject.IsDiscarded()) {
2740 LOGE("DecodeRequestAuth jsonStr error");
2741 return;
2742 }
2743 if (!IsString(jsonObject, TAG_DATA) || !IsInt32(jsonObject, TAG_DATA_LEN) || !IsInt32(jsonObject, TAG_MSG_TYPE)) {
2744 LOGE("Auth device data is error.");
2745 return;
2746 }
2747 LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].Get<int32_t>());
2748 std::string authData = jsonObject[TAG_DATA].Get<std::string>();
2749 int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();
2750 hiChainAuthConnector_->ProcessAuthData(authResponseContext_->requestId, authData, osAccountId);
2751 }
2752
DeleteGroup(const std::string & pkgName,const std::string & deviceId)2753 int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, const std::string &deviceId)
2754 {
2755 LOGI("DmAuthManager::DeleteGroup");
2756 if (pkgName.empty()) {
2757 LOGE("Invalid parameter, pkgName is empty.");
2758 return ERR_DM_FAILED;
2759 }
2760 std::vector<OHOS::DistributedHardware::GroupInfo> groupList;
2761 CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL);
2762 hiChainConnector_->GetRelatedGroups(deviceId, groupList);
2763 for (const auto &item : groupList) {
2764 std::string groupId = item.groupId;
2765 hiChainConnector_->DeleteGroup(groupId);
2766 }
2767 return DM_OK;
2768 }
2769
DeleteGroup(const std::string & pkgName,int32_t userId,const std::string & deviceId)2770 int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, int32_t userId, const std::string &deviceId)
2771 {
2772 LOGI("DmAuthManager::DeleteGroup");
2773 if (pkgName.empty()) {
2774 LOGE("Invalid parameter, pkgName is empty.");
2775 return ERR_DM_FAILED;
2776 }
2777 std::vector<OHOS::DistributedHardware::GroupInfo> groupList;
2778 hiChainConnector_->GetRelatedGroups(userId, deviceId, groupList);
2779 if (groupList.size() > 0) {
2780 std::string groupId = "";
2781 groupId = groupList.front().groupId;
2782 hiChainConnector_->DeleteGroup(userId, groupId);
2783 } else {
2784 LOGE("DmAuthManager::UnAuthenticateDevice groupList.size = 0");
2785 return ERR_DM_FAILED;
2786 }
2787 if (softbusConnector_ != nullptr) {
2788 softbusConnector_->EraseUdidFromMap(deviceId);
2789 }
2790 return DM_OK;
2791 }
2792
PutAccessControlList()2793 void DmAuthManager::PutAccessControlList()
2794 {
2795 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
2796 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
2797 std::string localUdid = static_cast<std::string>(localDeviceId);
2798 char mUdidHash[DM_MAX_DEVICE_ID_LEN] = {0};
2799 Crypto::GetUdidHash(localUdid, reinterpret_cast<uint8_t *>(mUdidHash));
2800 std::string localUdidHash = static_cast<std::string>(mUdidHash);
2801 DmAclInfo aclInfo;
2802 aclInfo.bindType = DM_ACROSS_ACCOUNT;
2803 if (authResponseContext_->localAccountId == "ohosAnonymousUid" ||
2804 authResponseContext_->remoteAccountId == "ohosAnonymousUid") {
2805 aclInfo.bindType = DM_POINT_TO_POINT;
2806 authForm_ = DmAuthForm::PEER_TO_PEER;
2807 }
2808 aclInfo.bindLevel = authResponseContext_->bindLevel;
2809 aclInfo.trustDeviceId = remoteDeviceId_;
2810 aclInfo.authenticationType = ALLOW_AUTH_ONCE;
2811 if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
2812 aclInfo.authenticationType = ALLOW_AUTH_ALWAYS;
2813 }
2814 aclInfo.deviceIdHash = localUdidHash;
2815 DmAccesser accesser;
2816 accesser.requestBundleName = authResponseContext_->hostPkgName;
2817 DmAccessee accessee;
2818 accessee.trustBundleName = authResponseContext_->peerBundleName;
2819 if (authRequestState_ != nullptr && authResponseState_ == nullptr) {
2820 PutSrcAccessControlList(accesser, accessee, localUdid);
2821 } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) {
2822 PutSinkAccessControlList(accesser, accessee, localUdid);
2823 }
2824 DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, accesser, accessee);
2825 }
2826
PutSrcAccessControlList(DmAccesser & accesser,DmAccessee & accessee,const std::string & localUdid)2827 void DmAuthManager::PutSrcAccessControlList(DmAccesser &accesser, DmAccessee &accessee,
2828 const std::string &localUdid)
2829 {
2830 accesser.requestTokenId = static_cast<uint64_t>(authRequestContext_->tokenId);
2831 accesser.requestUserId = authRequestContext_->localUserId;
2832 accesser.requestAccountId = authRequestContext_->localAccountId;
2833 accesser.requestDeviceId = authRequestContext_->localDeviceId;
2834 accesser.requestDeviceName = authRequestContext_->localDeviceName;
2835 if (authResponseContext_->remoteTokenId == authRequestContext_->tokenId) {
2836 accessee.trustTokenId = 0;
2837 } else {
2838 accessee.trustTokenId = static_cast<uint64_t>(authResponseContext_->remoteTokenId);
2839 }
2840 accessee.trustUserId = authRequestContext_->remoteUserId;
2841 accessee.trustAccountId = authRequestContext_->remoteAccountId;
2842 accessee.trustDeviceId = remoteDeviceId_;
2843 accessee.trustDeviceName = authRequestContext_->remoteDeviceName;
2844 }
2845
PutSinkAccessControlList(DmAccesser & accesser,DmAccessee & accessee,const std::string & localUdid)2846 void DmAuthManager::PutSinkAccessControlList(DmAccesser &accesser, DmAccessee &accessee,
2847 const std::string &localUdid)
2848 {
2849 accesser.requestTokenId = static_cast<uint64_t>(authResponseContext_->remoteTokenId);
2850 accesser.requestUserId = authResponseContext_->remoteUserId;
2851 accesser.requestAccountId = authResponseContext_->remoteAccountId;
2852 accesser.requestDeviceId = remoteDeviceId_;
2853 accesser.requestDeviceName = authResponseContext_->remoteDeviceName;
2854 if (authResponseContext_->remoteTokenId == authResponseContext_->tokenId) {
2855 accessee.trustTokenId = 0;
2856 } else {
2857 accessee.trustTokenId = static_cast<uint64_t>(authResponseContext_->tokenId);
2858 }
2859 accessee.trustUserId = authResponseContext_->localUserId;
2860 accessee.trustAccountId = authResponseContext_->localAccountId;
2861 accessee.trustDeviceId = localUdid;
2862 accessee.trustDeviceName = authResponseContext_->targetDeviceName;
2863 }
2864
HandleSessionHeartbeat(std::string name)2865 void DmAuthManager::HandleSessionHeartbeat(std::string name)
2866 {
2867 if (timer_ != nullptr) {
2868 timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK));
2869 }
2870 LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str());
2871 JsonObject jsonObj;
2872 jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT;
2873 std::string message = SafetyDump(jsonObj);
2874 softbusConnector_->GetSoftbusSession()->SendHeartbeatData(authResponseContext_->sessionId, message);
2875
2876 if (authRequestState_ != nullptr) {
2877 if (timer_ != nullptr) {
2878 timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK),
2879 GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) {
2880 DmAuthManager::HandleSessionHeartbeat(name);
2881 });
2882 }
2883 }
2884 LOGI("DmAuthManager::HandleSessionHeartbeat complete");
2885 }
2886
CheckTrustState()2887 int32_t DmAuthManager::CheckTrustState()
2888 {
2889 bool isSameGroup = false;
2890 if (authResponseContext_->reply == ERR_DM_AUTH_PEER_REJECT &&
2891 hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId,
2892 authRequestContext_->localDeviceId)) {
2893 isSameGroup = true;
2894 }
2895 if (isSameGroup && authResponseContext_->isOnline && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) {
2896 authResponseContext_->isFinish = true;
2897 SetReasonAndFinish(DM_OK, AuthState::AUTH_REQUEST_FINISH);
2898 return ALREADY_BIND;
2899 }
2900 if (authResponseContext_->isIdenticalAccount) {
2901 if (IsIdenticalAccount()) {
2902 JoinLnn(authResponseContext_->deviceId);
2903 authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
2904 authRequestContext_->reason = DM_OK;
2905 authResponseContext_->reply = DM_OK;
2906 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2907 return ALREADY_BIND;
2908 }
2909 }
2910 if (isSameGroup) {
2911 if (!DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(authResponseContext_->hostPkgName,
2912 authResponseContext_->localDeviceId)) {
2913 CompatiblePutAcl();
2914 }
2915 JoinLnn(authResponseContext_->deviceId);
2916 authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
2917 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2918 return ALREADY_BIND;
2919 }
2920 if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE ||
2921 (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE &&
2922 authResponseContext_->isAuthCodeReady == false)) {
2923 authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
2924 authRequestContext_->reason = ERR_DM_BIND_PEER_UNSUPPORTED;
2925 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
2926 return ERR_DM_BIND_PEER_UNSUPPORTED;
2927 }
2928 return DM_OK;
2929 }
2930
GetBundleLable(const std::string & bundleName)2931 std::string DmAuthManager::GetBundleLable(const std::string &bundleName)
2932 {
2933 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2934 if (samgr == nullptr) {
2935 LOGE("Get ability manager failed");
2936 return bundleName;
2937 }
2938
2939 sptr<IRemoteObject> object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
2940 if (object == nullptr) {
2941 LOGE("object is NULL.");
2942 return bundleName;
2943 }
2944
2945 sptr<OHOS::AppExecFwk::IBundleMgr> bms = iface_cast<OHOS::AppExecFwk::IBundleMgr>(object);
2946 if (bms == nullptr) {
2947 LOGE("bundle manager service is NULL.");
2948 return bundleName;
2949 }
2950
2951 auto bundleResourceProxy = bms->GetBundleResourceProxy();
2952 if (bundleResourceProxy == nullptr) {
2953 LOGE("GetBundleResourceProxy fail");
2954 return bundleName;
2955 }
2956 AppExecFwk::BundleResourceInfo resourceInfo;
2957 auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName,
2958 static_cast<uint32_t>(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo);
2959 if (result != ERR_OK) {
2960 LOGE("GetBundleResourceInfo failed");
2961 return bundleName;
2962 }
2963 LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str());
2964 return resourceInfo.label;
2965 }
2966
IsScreenLocked()2967 bool DmAuthManager::IsScreenLocked()
2968 {
2969 bool isLocked = false;
2970 #if defined(SUPPORT_SCREENLOCK)
2971 isLocked = OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked();
2972 #endif
2973 LOGI("IsScreenLocked isLocked: %{public}d.", isLocked);
2974 return isLocked;
2975 }
2976
OnScreenLocked()2977 void DmAuthManager::OnScreenLocked()
2978 {
2979 if (authResponseContext_ != nullptr && AUTH_TYPE_IMPORT_AUTH_CODE == authResponseContext_->authType) {
2980 LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", authResponseContext_->authType);
2981 return;
2982 }
2983 if (authRequestState_ == nullptr) {
2984 LOGE("OnScreenLocked authRequestState_ is nullptr.");
2985 return;
2986 }
2987 if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE ||
2988 authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_INIT) {
2989 LOGI("OnScreenLocked stop bind.");
2990 SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT);
2991 return;
2992 }
2993 if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_JOIN) {
2994 LOGI("OnScreenLocked stop user input.");
2995 if (authUiStateMgr_ != nullptr) {
2996 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT);
2997 }
2998 SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT);
2999 return;
3000 }
3001 if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_NEGOTIATE_DONE) {
3002 LOGI("OnScreenLocked stop confirm.");
3003 SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL, STATUS_DM_AUTH_DEFAULT);
3004 }
3005 }
3006
HandleDeviceNotTrust(const std::string & udid)3007 void DmAuthManager::HandleDeviceNotTrust(const std::string &udid)
3008 {
3009 LOGI("DmAuthManager::HandleDeviceNotTrust udid: %{public}s.", GetAnonyString(udid).c_str());
3010 if (udid.empty()) {
3011 LOGE("DmAuthManager::HandleDeviceNotTrust udid is empty.");
3012 return;
3013 }
3014 DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid);
3015 CHECK_NULL_VOID(hiChainConnector_);
3016 hiChainConnector_->DeleteAllGroupByUdid(udid);
3017 }
3018
ConvertSrcVersion(const std::string & version,const std::string & edition)3019 std::string DmAuthManager::ConvertSrcVersion(const std::string &version, const std::string &edition)
3020 {
3021 std::string srcVersion = "";
3022 if (version == "" && edition != "") {
3023 srcVersion = edition;
3024 } else if (version == "" && edition == "") {
3025 srcVersion = DM_VERSION_5_0_1;
3026 } else if (version != "" && edition == "") {
3027 srcVersion = version;
3028 }
3029 LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.",
3030 version.c_str(), edition.c_str(), srcVersion.c_str());
3031 return srcVersion;
3032 }
3033
ConvertSinkVersion(const std::string & version)3034 std::string DmAuthManager::ConvertSinkVersion(const std::string &version)
3035 {
3036 std::string sinkVersion = "";
3037 if (version == "") {
3038 sinkVersion = DM_VERSION_4_1_5_1;
3039 } else {
3040 sinkVersion = version;
3041 }
3042 LOGI("ConvertSinkVersion version %{public}s, sinkVersion is %{public}s.", version.c_str(), sinkVersion.c_str());
3043 return sinkVersion;
3044 }
3045
SetAuthType(int32_t authType)3046 void DmAuthManager::SetAuthType(int32_t authType)
3047 {
3048 authType_ = authType;
3049 }
3050
GetTaskTimeout(const char * taskName,int32_t taskTimeOut)3051 int32_t DmAuthManager::GetTaskTimeout(const char* taskName, int32_t taskTimeOut)
3052 {
3053 LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, authType_.load());
3054 if (AUTH_TYPE_IMPORT_AUTH_CODE == authType_) {
3055 auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName));
3056 if (timeout != TASK_TIME_OUT_MAP.end()) {
3057 return timeout->second;
3058 }
3059 }
3060 return taskTimeOut;
3061 }
3062
IsAllowDeviceBind()3063 bool DmAuthManager::IsAllowDeviceBind()
3064 {
3065 if (AppManager::GetInstance().IsSystemSA()) {
3066 return true;
3067 }
3068 return false;
3069 }
3070
GetBindLevel(int32_t bindLevel)3071 int32_t DmAuthManager::GetBindLevel(int32_t bindLevel)
3072 {
3073 #ifdef DEVICE_MANAGER_COMMON_FLAG
3074 LOGI("device_manager_common is true!");
3075 std::string processName = "";
3076 int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName);
3077 LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str());
3078 if (ret == DM_OK && CheckProcessNameInWhiteList(processName)) {
3079 return DEVICE;
3080 }
3081 #endif
3082 if (IsAllowDeviceBind()) {
3083 if (static_cast<uint32_t>(bindLevel) == INVALIED_TYPE || static_cast<uint32_t>(bindLevel) > APP ||
3084 static_cast<uint32_t>(bindLevel) < DEVICE) {
3085 return DEVICE;
3086 }
3087 return bindLevel;
3088 }
3089 if (static_cast<uint32_t>(bindLevel) == INVALIED_TYPE || (static_cast<uint32_t>(bindLevel) != APP &&
3090 static_cast<uint32_t>(bindLevel) != SERVICE)) {
3091 return APP;
3092 }
3093 return bindLevel;
3094 }
3095
GetBundleName(JsonObject & jsonObject)3096 std::string DmAuthManager::GetBundleName(JsonObject &jsonObject)
3097 {
3098 if (!jsonObject.IsDiscarded() && IsString(jsonObject, BUNDLE_NAME_KEY)) {
3099 return jsonObject[BUNDLE_NAME_KEY].Get<std::string>();
3100 }
3101 bool isSystemSA = false;
3102 std::string bundleName;
3103 AppManager::GetInstance().GetCallerName(isSystemSA, bundleName);
3104 return bundleName;
3105 }
3106
GetBinderInfo()3107 int32_t DmAuthManager::GetBinderInfo()
3108 {
3109 CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL);
3110 if (authResponseContext_->bundleName.empty()) {
3111 LOGI("bundleName is empty");
3112 authResponseContext_->localUserId = MultipleUserConnector::GetCurrentAccountUserID();
3113 authResponseContext_->localAccountId = MultipleUserConnector::GetOhosAccountId();
3114 return DM_OK;
3115 }
3116 authResponseContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId();
3117 authResponseContext_->localAccountId =
3118 MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId);
3119 if (authResponseContext_->peerBundleName == authResponseContext_->hostPkgName) {
3120 bundleName_ = authResponseContext_->bundleName;
3121 } else {
3122 bundleName_ = authResponseContext_->peerBundleName;
3123 }
3124 int32_t ret = AppManager::GetInstance().
3125 GetNativeTokenIdByName(authResponseContext_->bundleName, authResponseContext_->tokenId);
3126 if (ret == DM_OK) {
3127 LOGI("bundleName is sa");
3128 return DM_OK;
3129 }
3130 ret = AppManager::GetInstance().GetHapTokenIdByName(authResponseContext_->localUserId,
3131 authResponseContext_->peerBundleName, 0, authResponseContext_->tokenId);
3132 if (ret != DM_OK) {
3133 LOGI("get tokenId by bundleName failed %{public}s", GetAnonyString(authResponseContext_->bundleName).c_str());
3134 }
3135 return ret;
3136 }
3137
SetProcessInfo()3138 void DmAuthManager::SetProcessInfo()
3139 {
3140 CHECK_NULL_VOID(authResponseContext_);
3141 ProcessInfo processInfo;
3142 if (authResponseContext_->bindLevel == APP) {
3143 if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) {
3144 processInfo.pkgName = authResponseContext_->hostPkgName;
3145 processInfo.userId = authRequestContext_->localUserId;
3146 } else if ((authRequestState_ == nullptr) && (authResponseState_ != nullptr)) {
3147 processInfo.pkgName = authResponseContext_->peerBundleName;
3148 processInfo.userId = authResponseContext_->localUserId;
3149 } else {
3150 LOGE("DMAuthManager::SetProcessInfo failed, state is invalid.");
3151 }
3152 } else if (authResponseContext_->bindLevel == DEVICE || authResponseContext_->bindLevel == INVALIED_TYPE) {
3153 processInfo.pkgName = std::string(DM_PKG_NAME);
3154 processInfo.userId = authResponseContext_->localUserId;
3155 } else {
3156 LOGE("bindlevel error %{public}d.", authResponseContext_->bindLevel);
3157 return;
3158 }
3159 softbusConnector_->SetProcessInfo(processInfo);
3160 }
3161
ConverToFinish()3162 void DmAuthManager::ConverToFinish()
3163 {
3164 authRequestContext_->reason = DM_OK;
3165 authResponseContext_->reply = DM_OK;
3166 authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH;
3167 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
3168 }
3169
RequestReCheckMsg()3170 void DmAuthManager::RequestReCheckMsg()
3171 {
3172 LOGI("dmVersion %{public}s.", DM_VERSION_5_0_5);
3173 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
3174 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
3175 uint32_t tokenId = 0;
3176 int32_t localUserId = 0;
3177 MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, localUserId);
3178 std::string localAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(localUserId);
3179 authResponseContext_->edition = DM_VERSION_5_0_5;
3180 authResponseContext_->localDeviceId = static_cast<std::string>(localDeviceId);
3181 authResponseContext_->localUserId = localUserId;
3182 authResponseContext_->bundleName = authRequestContext_->hostPkgName;
3183 authResponseContext_->bindLevel = authRequestContext_->bindLevel;
3184 authResponseContext_->localAccountId = localAccountId;
3185 authResponseContext_->tokenId = authRequestContext_->tokenId;
3186 authMessageProcessor_->SetResponseContext(authResponseContext_);
3187 std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_RECHECK_MSG);
3188 softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
3189 }
3190
ResponseReCheckMsg()3191 void DmAuthManager::ResponseReCheckMsg()
3192 {
3193 LOGI("remoteVersion %{public}s, authResponseContext_->edition %{public}s.",
3194 remoteVersion_.c_str(), authResponseContext_->edition.c_str());
3195 if (!IsSinkMsgValid()) {
3196 LOGE("peer deviceId not trust.");
3197 authResponseContext_->isFinish = false;
3198 isFinishOfLocal_ = false;
3199 authMessageProcessor_->SetEncryptFlag(false);
3200 int32_t sessionId = authResponseContext_->sessionId;
3201 authResponseState_->TransitionTo(std::make_shared<AuthResponseFinishState>());
3202 return;
3203 }
3204 char localDeviceId[DEVICE_UUID_LENGTH] = {0};
3205 GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH);
3206 authResponseContext_->edition = DM_VERSION_5_0_5;
3207 authResponseContext_->localDeviceId = std::string(localDeviceId);
3208 authResponseContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId();
3209 authResponseContext_->localAccountId =
3210 MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId);
3211 if (AppManager::GetInstance().GetNativeTokenIdByName(bundleName_, authResponseContext_->tokenId) != DM_OK) {
3212 LOGE("BundleName %{public}s, GetNativeTokenIdByName failed.", GetAnonyString(bundleName_).c_str());
3213 if (AppManager::GetInstance().GetHapTokenIdByName(authResponseContext_->localUserId,
3214 bundleName_, 0, authResponseContext_->tokenId) != DM_OK) {
3215 LOGE("get tokenId by bundleName failed %{public}s", GetAnonyString(bundleName_).c_str());
3216 authResponseContext_->tokenId = 0;
3217 }
3218 }
3219 authResponseContext_->bundleName = authResponseContext_->peerBundleName;
3220 authMessageProcessor_->SetEncryptFlag(true);
3221 std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_RECHECK_MSG);
3222 softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message);
3223 PutAccessControlList();
3224 }
3225
RequestReCheckMsgDone()3226 void DmAuthManager::RequestReCheckMsgDone()
3227 {
3228 LOGI("remoteVersion %{public}s, authResponseContext_->edition %{public}s.",
3229 remoteVersion_.c_str(), authResponseContext_->edition.c_str());
3230 if (!IsSourceMsgValid()) {
3231 LOGE("peer deviceId not trust.");
3232 authResponseContext_->isFinish = false;
3233 isFinishOfLocal_ = false;
3234 authMessageProcessor_->SetEncryptFlag(false);
3235 authRequestState_->TransitionTo(std::make_shared<AuthRequestFinishState>());
3236 return;
3237 }
3238 authRequestState_->TransitionTo(std::make_shared<AuthRequestCredential>());
3239 PutAccessControlList();
3240 }
3241
IsSinkMsgValid()3242 bool DmAuthManager::IsSinkMsgValid()
3243 {
3244 if (authResponseContext_->edition != remoteVersion_ ||
3245 authResponseContext_->localDeviceId != remoteDeviceId_ ||
3246 authResponseContext_->localUserId != authResponseContext_->remoteUserId ||
3247 authResponseContext_->bundleName != authResponseContext_->hostPkgName ||
3248 authResponseContext_->localBindLevel != authResponseContext_->bindLevel) {
3249 return false;
3250 }
3251 return true;
3252 }
3253
IsSourceMsgValid()3254 bool DmAuthManager::IsSourceMsgValid()
3255 {
3256 if (authResponseContext_->edition != remoteVersion_ ||
3257 authResponseContext_->localDeviceId != remoteDeviceId_ ||
3258 authResponseContext_->localUserId != authRequestContext_->remoteUserId ||
3259 authResponseContext_->bundleName != authResponseContext_->peerBundleName ||
3260 authResponseContext_->localBindLevel != authResponseContext_->bindLevel) {
3261 return false;
3262 }
3263 authResponseContext_->localAccountId = authRequestContext_->localAccountId;
3264 return true;
3265 }
3266
RegisterAuthenticationType(int32_t authenticationType)3267 int32_t DmAuthManager::RegisterAuthenticationType(int32_t authenticationType)
3268 {
3269 if (authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH &&
3270 authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) {
3271 LOGE("Invalid parameter.");
3272 return ERR_DM_INPUT_PARA_INVALID;
3273 }
3274 authenticationType_ = authenticationType;
3275 return DM_OK;
3276 }
3277
ProcessReqPublicKey()3278 void DmAuthManager::ProcessReqPublicKey()
3279 {
3280 if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_AUTH_FINISH ||
3281 authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_RECHECK_MSG) {
3282 authResponseState_->TransitionTo(std::make_shared<AuthResponseCredential>());
3283 return;
3284 }
3285 if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) {
3286 std::lock_guard<std::mutex> lock(srcReqMsgLock_);
3287 isNeedProcCachedSrcReqMsg_ = true;
3288 }
3289 }
3290
GetLocalServiceInfoInDp()3291 void DmAuthManager::GetLocalServiceInfoInDp()
3292 {
3293 DistributedDeviceProfile::LocalServiceInfo localServiceInfo;
3294 int32_t result = DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType(
3295 authResponseContext_->hostPkgName, (int32_t)DMLocalServiceInfoPinExchangeType::FROMDP, localServiceInfo);
3296 if (result != DM_OK) {
3297 return;
3298 }
3299 if (IsLocalServiceInfoValid(localServiceInfo)) {
3300 serviceInfoProfile_ = localServiceInfo;
3301 LOGI("authBoxType %{public}d, authType %{public}d, pinExchangeType %{public}d",
3302 serviceInfoProfile_.GetAuthBoxType(), serviceInfoProfile_.GetAuthType(),
3303 serviceInfoProfile_.GetPinExchangeType());
3304 auto updateProfile = serviceInfoProfile_;
3305 updateProfile.SetPinCode("******");
3306 DeviceProfileConnector::GetInstance().UpdateLocalServiceInfo(updateProfile);
3307 }
3308 }
3309
CheckNeedShowAuthInfoDialog(int32_t errorCode)3310 bool DmAuthManager::CheckNeedShowAuthInfoDialog(int32_t errorCode)
3311 {
3312 CHECK_NULL_RETURN(authResponseContext_, false);
3313 if (errorCode == ERR_DM_HICHAIN_PROOFMISMATCH && !pincodeDialogEverShown_ && CanUsePincodeFromDp()) {
3314 authResponseContext_->code = GeneratePincode();
3315 LOGI("AuthDeviceError, GeneratePincode, ShowAuthInfoDialog");
3316 authTimes_ = 0;
3317 ShowAuthInfoDialog(true);
3318 return true;
3319 }
3320 return false;
3321 }
3322
UpdateInputPincodeDialog(int32_t errorCode)3323 void DmAuthManager::UpdateInputPincodeDialog(int32_t errorCode)
3324 {
3325 CHECK_NULL_VOID(authResponseContext_);
3326 CHECK_NULL_VOID(authUiStateMgr_);
3327 if (authResponseContext_->authType == AUTH_TYPE_NFC && !pincodeDialogEverShown_ &&
3328 IsImportedAuthCodeValid() && errorCode == ERR_DM_HICHAIN_PROOFMISMATCH) {
3329 LOGI("AuthDeviceError, ShowStartAuthDialog");
3330 authTimes_ = 0;
3331 DeleteAuthCode();
3332 ShowStartAuthDialog();
3333 } else {
3334 authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR);
3335 }
3336 }
3337
JoinLnn(const std::string & deviceId,bool isForceJoin)3338 void DmAuthManager::JoinLnn(const std::string &deviceId, bool isForceJoin)
3339 {
3340 CHECK_NULL_VOID(authRequestContext_);
3341 CHECK_NULL_VOID(authResponseContext_);
3342 CHECK_NULL_VOID(softbusConnector_);
3343 if (IsHmlSessionType()) {
3344 if (authRequestContext_->closeSessionDelaySeconds == 0) {
3345 isWaitingJoinLnnCallback_ = true;
3346 }
3347 authResponseContext_->localSessionKeyId = GetSessionKeyIdSync(authResponseContext_->requestId);
3348 softbusConnector_->JoinLnnByHml(authRequestContext_->sessionId, authResponseContext_->localSessionKeyId,
3349 authResponseContext_->remoteSessionKeyId);
3350 return;
3351 }
3352 softbusConnector_->JoinLnn(deviceId, isForceJoin);
3353 }
3354
GetTokenIdByBundleName(int32_t userId,std::string & bundleName,int64_t & tokenId)3355 int32_t DmAuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId)
3356 {
3357 int32_t ret = AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tokenId);
3358 if (ret == DM_OK) {
3359 return DM_OK;
3360 }
3361 ret = AppManager::GetInstance().GetHapTokenIdByName(userId, bundleName, 0, tokenId);
3362 if (ret != DM_OK) {
3363 LOGE("get tokenId by bundleName failed %{public}s", GetAnonyString(bundleName).c_str());
3364 }
3365 return ret;
3366 }
3367
OnSoftbusJoinLNNResult(const int32_t sessionId,const char * networkId,int32_t result)3368 void DmAuthManager::OnSoftbusJoinLNNResult(const int32_t sessionId, const char *networkId, int32_t result)
3369 {
3370 (void)networkId;
3371 (void)result;
3372 CloseAuthSession(sessionId);
3373 }
3374
CloseAuthSession(const int32_t sessionId)3375 void DmAuthManager::CloseAuthSession(const int32_t sessionId)
3376 {
3377 if (timer_ != nullptr) {
3378 timer_->DeleteTimer(std::string(WAIT_SESSION_CLOSE_TIMEOUT_TASK) + std::string(CLOSE_SESSION_TASK_SEPARATOR) +
3379 std::to_string(sessionId));
3380 }
3381 CHECK_NULL_VOID(softbusConnector_);
3382 CHECK_NULL_VOID(softbusConnector_->GetSoftbusSession());
3383 softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId);
3384 }
3385 } // namespace DistributedHardware
3386 } // namespace OHOS
3387