From 2e7629f3878bc235553dc99f9f274e3f4eaa4a6f Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Thu, 24 Apr 2025 17:56:12 +0800 Subject: [PATCH 1/5] remove device name privacy info Signed-off-by: hwzhangchuang --- .../idevice_manager_service_listener.h | 7 + .../src/authentication_v2/auth_manager.cpp | 4 +- .../auth_stages/auth_negotiate.cpp | 2 +- services/service/BUILD.gn | 4 - .../include/device_manager_service_listener.h | 2 + .../devicenamemgr/account_boot_listener.h | 54 ---- .../devicenamemgr/device_name_manager.h | 18 ++ .../devicenamemgr/local_device_name_mgr.h | 53 ---- .../settings_data_event_monitor.h | 41 --- .../src/device_manager_service_listener.cpp | 5 + .../devicenamemgr/account_boot_listener.cpp | 176 ----------- .../src/devicenamemgr/device_name_manager.cpp | 88 ++++++ .../devicenamemgr/local_device_name_mgr.cpp | 293 ------------------ .../settings_data_event_monitor.cpp | 54 ---- test/unittest/UTTest_dm_pin_holder.h | 5 + 15 files changed, 128 insertions(+), 678 deletions(-) delete mode 100644 services/service/include/devicenamemgr/account_boot_listener.h delete mode 100644 services/service/include/devicenamemgr/local_device_name_mgr.h delete mode 100644 services/service/include/devicenamemgr/settings_data_event_monitor.h delete mode 100644 services/service/src/devicenamemgr/account_boot_listener.cpp delete mode 100644 services/service/src/devicenamemgr/local_device_name_mgr.cpp delete mode 100644 services/service/src/devicenamemgr/settings_data_event_monitor.cpp diff --git a/interfaces/inner_kits/native_cpp/include/idevice_manager_service_listener.h b/interfaces/inner_kits/native_cpp/include/idevice_manager_service_listener.h index 0673eef76..97146133d 100644 --- a/interfaces/inner_kits/native_cpp/include/idevice_manager_service_listener.h +++ b/interfaces/inner_kits/native_cpp/include/idevice_manager_service_listener.h @@ -171,6 +171,13 @@ public: const std::string &deviceName, int32_t code) = 0; virtual void OnSetRemoteDeviceNameResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &deviceName, int32_t code) = 0; + + /** + * @brief Get the Local Display Device Name after privacy processed + * + * @return std::string the name without privacy info + */ + virtual std::string GetLocalDisplayDeviceNameForPrivacy() = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 86722fb50..563a4dadb 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -23,6 +23,7 @@ #include "deviceprofile_connector.h" #include "multiple_user_connector.h" +#include "auth_manager.h" #include "dm_constants.h" #include "dm_crypto.h" #include "dm_random.h" @@ -34,7 +35,6 @@ #include "dm_auth_state_machine.h" #include "dm_auth_context.h" #include "dm_auth_message_processor.h" -#include "auth_manager.h" #include "dm_auth_state.h" namespace OHOS { @@ -548,7 +548,7 @@ void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, context_->pkgName = pkgName; context_->pkgLabel = GetBundleLabel(pkgName); context_->authType = (DmAuthType)authType; - context_->accesser.deviceName = context_->softbusConnector->GetLocalDeviceName(); + context_->accesser.deviceName = context_->listener->GetLocalDisplayDeviceNameForPrivacy(); context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); context_->accesser.isOnline = false; uint32_t callingTokenId = 0; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index c1c63bc3b..2e8d3d892 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -154,7 +154,7 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.tokenIdHash = Crypto::Sha256(std::to_string(context->accessee.tokenId)); context->accesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceIdHash, true); context->accessee.language = DmLanguageManager::GetInstance().GetSystemLanguage(); - context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); + context->accessee.deviceName = context->listener->GetLocalDisplayDeviceNameForPrivacy(); context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); return DM_OK; } diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index 48209cbdb..a7e1c6366 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -206,8 +206,6 @@ if (defined(ohos_lite)) { "src/device_manager_service_listener.cpp", "src/devicenamemgr/device_name_change_monitor.cpp", "src/devicenamemgr/device_name_manager.cpp", - "src/devicenamemgr/local_device_name_mgr.cpp", - "src/devicenamemgr/settings_data_event_monitor.cpp", "src/discovery/discovery_filter.cpp", "src/discovery/discovery_manager.cpp", "src/hichain/hichain_listener.cpp", @@ -348,8 +346,6 @@ if (defined(ohos_lite)) { "src/device_manager_service_listener.cpp", "src/devicenamemgr/device_name_change_monitor.cpp", "src/devicenamemgr/device_name_manager.cpp", - "src/devicenamemgr/local_device_name_mgr.cpp", - "src/devicenamemgr/settings_data_event_monitor.cpp", "src/discovery/discovery_filter.cpp", "src/discovery/discovery_manager.cpp", "src/hichain/hichain_listener.cpp", diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 9766358fb..a2a02d3e7 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -90,6 +90,8 @@ public: void OnSetRemoteDeviceNameResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &deviceName, int32_t code) override; + std::string GetLocalDisplayDeviceNameForPrivacy() override; + private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); diff --git a/services/service/include/devicenamemgr/account_boot_listener.h b/services/service/include/devicenamemgr/account_boot_listener.h deleted file mode 100644 index a7aa62935..000000000 --- a/services/service/include/devicenamemgr/account_boot_listener.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_ACCOUNT_BOOT_LISTENER_H -#define OHOS_ACCOUNT_BOOT_LISTENER_H - -#include "local_device_name_mgr.h" -namespace OHOS { -namespace DistributedHardware { -enum class SaTriggerFlag : int32_t { - DM_SA_READY = 0, - DATA_SHARE_SA_REDDY = 1 -}; - -class AccountBootListener { -public: - AccountBootListener(); - ~AccountBootListener(); - void RegisterAccountBootCb(); - void DoAccountBootProc(); - void SetSaTriggerFlag(SaTriggerFlag triggerFlag); - void InitDataShareEvent(); - void DataShareCallback(); - std::string GetLocalDisplayName() const; - std::string GetLocalDeviceName() const; - -private: - /** - * @brief flag for is registered callback for account boot event - * true: has register the callback - * false: NOT register the callback - */ - std::atomic isRegAccountBootCb_; - std::shared_ptr localDeviceMgr_; - std::atomic isDmSaReady_; - std::atomic isDataShareReady_; - static std::mutex depSaStatelock_; - std::shared_ptr dataShareCommonEventManager_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_ACCOUNT_BOOT_LISTENER_H \ No newline at end of file diff --git a/services/service/include/devicenamemgr/device_name_manager.h b/services/service/include/devicenamemgr/device_name_manager.h index 50670c762..c2df78f71 100644 --- a/services/service/include/devicenamemgr/device_name_manager.h +++ b/services/service/include/devicenamemgr/device_name_manager.h @@ -45,6 +45,7 @@ public: int32_t RestoreLocalDeviceName(); int32_t InitDeviceNameWhenLanguageOrRegionChanged(); + std::string GetLocalDisplayDeviceNameForPrivacy(); private: DeviceNameManager() = default; ~DeviceNameManager() = default; @@ -56,6 +57,23 @@ private: std::string GetLocalDisplayDeviceName(const std::string &prefixName, const std::string &subffixName, int32_t maxNamelength); std::string SubstrByBytes(const std::string &str, int32_t maxNumBytes); + /** + * @brief Convert the raw string to whole character, consider character encoding, such as One Chinese + * letter maybe encoded to 3 bytes. + * + * @param str raw string + * @return std::string string in encoded letter. + */ + std::vector ConvertToWholeCharacter(const std::string &str); + /** + * @brief anonymize the string middle part, left begin and end 3 letter, the middle part set "***" + * + * @param str the raw string + * @return std::string the string processed + */ + std::string AnoyPrivacyString(const std::string &str); + std::string GenLocalAnoyDeviceNameWithNickAndMarketName(const std::string &nickName, + const std::string &marketName); std::string GetSystemLanguage(); std::string GetSystemRegion(); diff --git a/services/service/include/devicenamemgr/local_device_name_mgr.h b/services/service/include/devicenamemgr/local_device_name_mgr.h deleted file mode 100644 index 53f7a6153..000000000 --- a/services/service/include/devicenamemgr/local_device_name_mgr.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DEVICE_NAME_MGR_H -#define OHOS_DEVICE_NAME_MGR_H - -#include "datashare_helper.h" - -namespace OHOS { -namespace DistributedHardware { -class LocalDeviceNameMgr : public std::enable_shared_from_this { -public: - LocalDeviceNameMgr(); - virtual ~LocalDeviceNameMgr(); - int32_t QueryLocalDeviceName(); - void RegisterDeviceNameChangeCb(); - int32_t QueryLocalDisplayName(); - void RegisterDisplayNameChangeCb(); - std::string GetLocalDisplayName() const; - std::string GetLocalDeviceName() const; - -private: - std::shared_ptr GetDataShareHelper(); - int32_t GetDeviceNameFromDataShareHelper(std::shared_ptr dataShareHelper, - std::shared_ptr uri, const char *key, std::string &deviceName); - int32_t GetDefaultDeviceName(std::shared_ptr dataShareHelper, - std::string &deviceName); - int32_t GetUserDefinedDeviceName(std::shared_ptr dataShareHelper, - std::string &deviceName); - int32_t GetDisplayDeviceName(std::shared_ptr dataShareHelper, - std::string &deviceName); - int32_t GetActiveOsAccountIds(); -private: - static std::mutex devNameMtx_; - std::string localDeviceName_; - std::string localDisplayName_; -}; -} // DistributedHardware -} // OHOS - -#endif // OHOS_DEVICE_NAME_MGR_H \ No newline at end of file diff --git a/services/service/include/devicenamemgr/settings_data_event_monitor.h b/services/service/include/devicenamemgr/settings_data_event_monitor.h deleted file mode 100644 index 68c9cd92c..000000000 --- a/services/service/include/devicenamemgr/settings_data_event_monitor.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_SETTINGS_DATA_EVENT_MONITOR_H -#define OHOS_SETTINGS_DATA_EVENT_MONITOR_H - -#include "data_ability_observer_stub.h" -#include "local_device_name_mgr.h" - -namespace OHOS { -namespace DistributedHardware { -class LocalDeviceNameMgr; -enum class SettingsDataMonitorType : int32_t { - USER_DEFINED_DEVICE_NAME_MONITOR = 0, - DISPLAY_DEVICE_NAME_MONITOR = 1 -}; - -class SettingsDataEventMonitor : public AAFwk::DataAbilityObserverStub { -public: - SettingsDataEventMonitor(std::shared_ptr localDeviceNameMgr, - SettingsDataMonitorType monitorType); - void OnChange() override; -private: - std::weak_ptr localDeviceNameMgrWPtr_; - SettingsDataMonitorType monitorType_; -}; -} // DistributedHardware -} // OHOS -#endif // OHOS_SETTINGS_DATA_EVENT_MONITOR_H \ No newline at end of file diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index ba30c6d62..72d1c475e 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -996,5 +996,10 @@ void DeviceManagerServiceListener::OnSetRemoteDeviceNameResult(const ProcessInfo pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SET_REMOTE_DEVICE_NAME_RESULT, pReq, pRsp); } + +std::string DeviceManagerServiceListener::GetLocalDisplayDeviceNameForPrivacy() +{ + return DeviceNameManager::GetInstance().GetLocalDisplayDeviceNameForPrivacy(); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/devicenamemgr/account_boot_listener.cpp b/services/service/src/devicenamemgr/account_boot_listener.cpp deleted file mode 100644 index 1149c3975..000000000 --- a/services/service/src/devicenamemgr/account_boot_listener.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "account_boot_listener.h" -#include "common_event_support.h" -#include "parameter.h" - -#include "dm_log.h" -#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) -#include "ffrt.h" -#endif - -namespace OHOS { -namespace DistributedHardware { -namespace { - const char * const BOOTEVENT_ACCOUNT_READY = "bootevent.account.ready"; -#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) - const char * const ACCOUNT_BOOT_EVENT = "account_boot_event"; -#endif -} - -std::mutex AccountBootListener::depSaStatelock_; - -static void AccountBootCb(const char *key, const char *value, void *context) -{ - if (key == nullptr || value == nullptr || context == nullptr) { - LOGE("key or value or context is null, param is error!"); - return; - } - if (strcmp(key, BOOTEVENT_ACCOUNT_READY) != 0 || strcmp(value, "true") != 0) { - return; - } - AccountBootListener *accountBootListener = static_cast(context); - - if (accountBootListener == nullptr) { - LOGE("accountBootListener is null"); - return; - } - LOGI("Trigger"); -#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::submit([=]() { accountBootListener->DoAccountBootProc(); }); -#else - std::thread dealThread([=]() { - accountBootListener->DoAccountBootProc(); - }); - int32_t ret = pthread_setname_np(dealThread.native_handle(), ACCOUNT_BOOT_EVENT); - if (ret != DM_OK) { - LOGE("dealThread setname failed."); - } - dealThread.detach(); -#endif -} - -AccountBootListener::AccountBootListener() : isRegAccountBootCb_(false), - localDeviceMgr_(std::make_shared()), isDmSaReady_(false), isDataShareReady_(false), - dataShareCommonEventManager_(std::make_shared()) -{ - LOGI("Ctor AccountBootListener"); -} - -AccountBootListener::~AccountBootListener() -{ - LOGI("Dtor AccountBootListener"); -} - -void AccountBootListener::RegisterAccountBootCb() -{ - if (isRegAccountBootCb_) { - return; - } - LOGI("start"); - int32_t ret = WatchParameter(BOOTEVENT_ACCOUNT_READY, AccountBootCb, this); - if (ret != 0) { - LOGE("watch account boot event fail"); - } - isRegAccountBootCb_ = true; -} - -void AccountBootListener::DoAccountBootProc() -{ - LOGI("start"); - if (localDeviceMgr_ == nullptr) { - LOGE("localDeviceMgr_ is null"); - return; - } - localDeviceMgr_->RegisterDeviceNameChangeCb(); - localDeviceMgr_->RegisterDisplayNameChangeCb(); - localDeviceMgr_->QueryLocalDisplayName(); - localDeviceMgr_->QueryLocalDeviceName(); -} - -void AccountBootListener::SetSaTriggerFlag(SaTriggerFlag triggerFlag) -{ - LOGI("start"); - std::lock_guard lock(depSaStatelock_); - switch (triggerFlag) { - case SaTriggerFlag::DM_SA_READY: - isDmSaReady_ = true; - LOGI("DM SA ready!"); - break; - case SaTriggerFlag::DATA_SHARE_SA_REDDY: - LOGI("DATA SHARE SA ready!"); - this->InitDataShareEvent(); - break; - default: - break; - } - LOGI("isDmSaReady_: %{public}d, isDataShareReady_: %{public}d", - std::atomic_load(&isDmSaReady_), std::atomic_load(&isDataShareReady_)); - if (isDmSaReady_ && isDataShareReady_) { - LOGI("dm and data_share is ready!"); - this->RegisterAccountBootCb(); - } -} - -void AccountBootListener::InitDataShareEvent() -{ - LOGI("Start"); - if (dataShareCommonEventManager_ == nullptr) { - dataShareCommonEventManager_ = std::make_shared(); - } - DataShareEventCallback callback = [=]() { - this->DataShareCallback(); - }; - std::vector dataShareEventVec; - dataShareEventVec.emplace_back(EventFwk::CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY); - if (dataShareCommonEventManager_->SubscribeDataShareCommonEvent(dataShareEventVec, callback)) { - LOGI("Success"); - } - return; -} - -void AccountBootListener::DataShareCallback() -{ - LOGI("Start"); - std::lock_guard lock(depSaStatelock_); - isDataShareReady_ = true; - LOGI("isDmSaReady_: %{public}d, isDataShareReady_: %{public}d", - std::atomic_load(&isDmSaReady_), std::atomic_load(&isDataShareReady_)); - if (isDmSaReady_ && isDataShareReady_) { - LOGI("dm and data_share is ready!"); - this->RegisterAccountBootCb(); - } -} - -std::string AccountBootListener::GetLocalDisplayName() const -{ - if (localDeviceMgr_ == nullptr) { - LOGE("logcalDeviceMgr_ is null"); - return ""; - } - return localDeviceMgr_->GetLocalDisplayName(); -} - -std::string AccountBootListener::GetLocalDeviceName() const -{ - if (localDeviceMgr_ == nullptr) { - LOGE("logcalDeviceMgr_ is null"); - return ""; - } - return localDeviceMgr_->GetLocalDeviceName(); -} -} // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file diff --git a/services/service/src/devicenamemgr/device_name_manager.cpp b/services/service/src/devicenamemgr/device_name_manager.cpp index a2d7964c6..87472bf13 100644 --- a/services/service/src/devicenamemgr/device_name_manager.cpp +++ b/services/service/src/devicenamemgr/device_name_manager.cpp @@ -41,13 +41,16 @@ const std::string SETTINGS_GENERAL_USER_DEFINED_DEVICE_NAME = "settings.general. const std::string SETTINGS_GENERAL_DISPLAY_DEVICE_NAME_STATE = "settings.general.display_device_name_state"; const std::string SETTING_COLUMN_VALUE = "VALUE"; const std::string SETTING_COLUMN_KEYWORD = "KEYWORD"; +constexpr int32_t NUM0 = 0; constexpr int32_t NUM1 = 1; constexpr int32_t NUM2 = 2; constexpr int32_t NUM3 = 3; constexpr int32_t NUM4 = 4; +constexpr int32_t NUM6 = 6; constexpr int32_t NUM18 = 18; constexpr int32_t NUM21 = 21; constexpr int32_t NUM24 = 24; +const std::string ANOY_STRING = "***"; constexpr int32_t DEFAULT_DEVICE_NAME_MAX_LENGTH = 12; constexpr int32_t NAME_LENGTH_MIN = 18; constexpr int32_t NAME_LENGTH_MAX = 100; @@ -336,6 +339,32 @@ int32_t DeviceNameManager::GetLocalDisplayDeviceName(int32_t maxNamelength, std: return DM_OK; } +std::string DeviceNameManager::GenLocalAnoyDeviceNameWithNickAndMarketName(const std::string &nickName, + const std::string &marketName) +{ + std::string anoyNickName = AnoyPrivacyString(nickName); + std::string nameSeparator = NAME_SEPARATOR_ZH; + if (GetSystemLanguage() != LANGUAGE_ZH_HANS || GetSystemRegion() != LOCAL_ZH_HANS_CN) { + nameSeparator = NAME_SEPARATOR_OTHER; + } + + return anoyNickName + nameSeparator + marketName; +} + +std::string DeviceNameManager::GetLocalDisplayDeviceNameForPrivacy() +{ + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + std::string userDefinedDeviceName = ""; + GetUserDefinedDeviceName(userId, userDefinedDeviceName); + if (!userDefinedDeviceName.empty()) { + return AnoyPrivacyString(userDefinedDeviceName); + } + + std::string nickName = MultipleUserConnector::GetAccountNickName(userId); + std::string localMarketName = GetLocalMarketName(); + return GenLocalAnoyDeviceNameWithNickAndMarketName(nickName, localMarketName); +} + std::string DeviceNameManager::GetLocalDisplayDeviceName(const std::string &prefixName, const std::string &subffixName, int32_t maxNameLength) { @@ -423,6 +452,65 @@ int32_t DeviceNameManager::GetUserDefinedDeviceName(int32_t userId, std::string return GetValue(SETTINGSDATA_SECURE, userId, SETTINGS_GENERAL_USER_DEFINED_DEVICE_NAME, deviceName); } +std::string DeviceNameManager::AnoyPrivacyString(const std::string &str) +{ + std::vector wholeCharVec = ConvertToWholeCharacter(str); + if (wholeCharVec.size() == NUM0) { + return ""; + } + if (wholeCharVec.size() == NUM1) { + return wholeCharVec[1]; + } + + std::string res; + if (wholeCharVec.size() > NUM1 && wholeCharVec.size() <= NUM6) { + uint32_t leftLen = wholeCharVec.size() / 2; + for (uint32_t i = 0; i < leftLen; i++) { + res += wholeCharVec[i]; + } + res += ANOY_STRING; + return res; + } + + for (int32_t i = 0; i < NUM3; i++) { + res += wholeCharVec[i]; + } + res += ANOY_STRING; + for (int32_t j = wholeCharVec.size() - NUM3; j < wholeCharVec.size(); j++) { + res += wholeCharVec[j]; + } + return res; +} + +std::vector DeviceNameManager::ConvertToWholeCharacter(const std::string &str) +{ + std::vector wholeCharacterVec; + int32_t length = static_cast(str.size()); + for (int32_t i = 0; i < length;) { + unsigned char c = static_cast(str[i]); + int numBytes = NUM1; + if ((c & 0x80) == 0) { + numBytes = NUM1; + } else if ((c & 0xE0) == 0xC0) { + numBytes = NUM2; + } else if ((c & 0xF0) == 0xE0) { + numBytes = NUM3; + } else if ((c & 0xF8) == 0xF0) { + numBytes = NUM4; + } else { + LOGE("Invalid characters"); + return {}; + } + if (i + numBytes > length) { + break; + } + std::string substr(str.begin() + i, str.begin() + i + numBytes); + wholeCharacterVec.emplace_back(substr); + i += numBytes; + } + return wholeCharacterVec; +} + std::string DeviceNameManager::SubstrByBytes(const std::string &str, int32_t maxNumBytes) { int32_t length = static_cast(str.size()); diff --git a/services/service/src/devicenamemgr/local_device_name_mgr.cpp b/services/service/src/devicenamemgr/local_device_name_mgr.cpp deleted file mode 100644 index 4c9e616ba..000000000 --- a/services/service/src/devicenamemgr/local_device_name_mgr.cpp +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Copyright (c) 2024-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "local_device_name_mgr.h" - -#include "datashare_result_set.h" -#include "ohos_account_kits.h" -#include "os_account_manager.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" -#include "uri.h" - -#include "device_manager_service.h" -#include "dm_error_type.h" -#include "dm_log.h" -#include "settings_data_event_monitor.h" - -namespace OHOS { -namespace DistributedHardware { -namespace { - const std::string SETTINGS_DATA_BASE_URI = - "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true"; - const std::string SETTINGS_DATA_SECURE_URI = - "datashare:///com.ohos.settingsdata/entry/settingsdata/USER_SETTINGSDATA_SECURE_"; - constexpr const char *SETTINGS_DATA_EXT_URI = "datashare:///com.ohos.settingsdata.DataAbility"; - constexpr const char *SETTINGS_DATA_FIELD_KEYWORD = "KEYWORD"; - constexpr const char *SETTINGS_DATA_FIELD_VALUE = "VALUE"; - constexpr const char *PREDICATES_STRING = "settings.general.device_name"; - constexpr const char *USER_DEFINED_STRING = "settings.general.user_defined_device_name"; - constexpr const char *DISPLAY_DEVICE_NAME_STRING = "settings.general.display_device_name"; -} - -std::mutex LocalDeviceNameMgr::devNameMtx_; - -LocalDeviceNameMgr::LocalDeviceNameMgr() : localDeviceName_(""), localDisplayName_("") -{ - LOGI("Ctor LocalDeviceNameMgr"); -} - -LocalDeviceNameMgr::~LocalDeviceNameMgr() -{ - std::lock_guard lock(devNameMtx_); - localDeviceName_ = ""; - localDisplayName_ = ""; - LOGI("Dtor LocalDeviceNameMgr"); -} - -std::shared_ptr LocalDeviceNameMgr::GetDataShareHelper() -{ - sptr saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (saManager == nullptr) { - LOGE("saManager NULL"); - return nullptr; - } - - sptr remoteObject = saManager->GetSystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); - if (remoteObject == nullptr) { - LOGE("remoteObject NULL"); - return nullptr; - } - return DataShare::DataShareHelper::Creator(remoteObject, SETTINGS_DATA_BASE_URI, SETTINGS_DATA_EXT_URI); -} - -int32_t LocalDeviceNameMgr::GetDeviceNameFromDataShareHelper( - std::shared_ptr dataShareHelper, std::shared_ptr uri, - const char *key, std::string &deviceName) -{ - if (dataShareHelper == nullptr || uri == nullptr || key == nullptr) { - LOGE("dataShareHelper or uri or key is null, param is error!"); - return ERR_DM_FAILED; - } - int32_t numRows = 0; - std::string val; - std::vector columns; - columns.emplace_back(SETTINGS_DATA_FIELD_VALUE); - DataShare::DataSharePredicates predicates; - predicates.EqualTo(SETTINGS_DATA_FIELD_KEYWORD, key); - - auto resultSet = dataShareHelper->Query(*uri, predicates, columns); - if (resultSet == nullptr) { - LOGE("query fail."); - return ERR_DM_FAILED; - } - resultSet->GetRowCount(numRows); - if (numRows <= 0) { - LOGE("row zero."); - resultSet->Close(); - return ERR_DM_FAILED; - } - - int columnIndex; - resultSet->GoToFirstRow(); - resultSet->GetColumnIndex(SETTINGS_DATA_FIELD_VALUE, columnIndex); - if (resultSet->GetString(columnIndex, val) != DM_OK) { - LOGE("GetString val fail"); - resultSet->Close(); - return ERR_DM_FAILED; - } - deviceName = val; - LOGI("deviceName=%{public}s.", deviceName.c_str()); - resultSet->Close(); - return DM_OK; -} - -int32_t LocalDeviceNameMgr::GetDefaultDeviceName(std::shared_ptr dataShareHelper, - std::string &deviceName) -{ - if (dataShareHelper == nullptr) { - LOGE("dataShareHelper is null, param is error!"); - return ERR_DM_FAILED; - } - std::shared_ptr uri = std::make_shared(SETTINGS_DATA_BASE_URI + "&key=" + PREDICATES_STRING); - LOGI("get default deviceName"); - return GetDeviceNameFromDataShareHelper(dataShareHelper, uri, PREDICATES_STRING, deviceName); -} - -int32_t LocalDeviceNameMgr::GetUserDefinedDeviceName(std::shared_ptr dataShareHelper, - std::string &deviceName) -{ - if (dataShareHelper == nullptr) { - LOGE("dataShareHelper is null, param is error!"); - return ERR_DM_FAILED; - } - int32_t osAccountId = GetActiveOsAccountIds(); - if (osAccountId == ERR_DM_FAILED) { - LOGE("osAccountId acquire fail!"); - return ERR_DM_FAILED; - } - std::string accountIdStr = std::to_string(osAccountId); - std::shared_ptr uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + "?Proxy=true&key=" + - USER_DEFINED_STRING); - LOGI("get user defined deviceName, accountId=%{public}s", accountIdStr.c_str()); - return GetDeviceNameFromDataShareHelper(dataShareHelper, uri, USER_DEFINED_STRING, deviceName); -} - -int32_t LocalDeviceNameMgr::GetDisplayDeviceName(std::shared_ptr dataShareHelper, - std::string &deviceName) -{ - if (dataShareHelper == nullptr) { - LOGE("dataShareHelper is null, param is error!"); - return ERR_DM_FAILED; - } - int32_t osAccountId = GetActiveOsAccountIds(); - if (osAccountId == ERR_DM_FAILED) { - LOGE("osAccountId acquire fail!"); - return ERR_DM_FAILED; - } - std::string accountIdStr = std::to_string(osAccountId); - std::shared_ptr uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + "?Proxy=true&key=" + - DISPLAY_DEVICE_NAME_STRING); - LOGI("get user defined deviceName, accountId=%{public}s", accountIdStr.c_str()); - return GetDeviceNameFromDataShareHelper(dataShareHelper, uri, DISPLAY_DEVICE_NAME_STRING, deviceName); -} - -int32_t LocalDeviceNameMgr::GetActiveOsAccountIds() -{ - std::vector accountId; - int32_t ret = OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(accountId); - if (ret != DM_OK || accountId.empty()) { - LOGE("QueryActiveOsAccountIds failed"); - return ERR_DM_FAILED; - } - LOGI("account id=%{public}d", accountId[0]); - return accountId[0]; -} - -int32_t LocalDeviceNameMgr::QueryLocalDeviceName() -{ - auto dataShareHelper = GetDataShareHelper(); - if (dataShareHelper == nullptr) { - LOGE("dataShareHelper is null"); - return ERR_DM_FAILED; - } - std::string localDeviceName = ""; - int32_t ret = GetUserDefinedDeviceName(dataShareHelper, localDeviceName); - if (ret == DM_OK && !localDeviceName.empty()) { - std::lock_guard lock(devNameMtx_); - localDeviceName_ = localDeviceName; - dataShareHelper->Release(); - LOGI("get user defined deviceName=%{public}s", localDeviceName.c_str()); - - return DM_OK; - } - ret = GetDefaultDeviceName(dataShareHelper, localDeviceName); - if (ret != DM_OK || localDeviceName.empty()) { - LOGE("get default deviceName failed"); - return ERR_DM_FAILED; - } - std::lock_guard lock(devNameMtx_); - localDeviceName_ = localDeviceName; - dataShareHelper->Release(); - LOGI("get default deviceName=%{public}s", localDeviceName.c_str()); - - return DM_OK; -} - -void LocalDeviceNameMgr::RegisterDeviceNameChangeCb() -{ - auto dataShareHelper = GetDataShareHelper(); - if (dataShareHelper == nullptr) { - LOGE("dataShareHelper is null"); - return; - } - - auto uri = std::make_shared(SETTINGS_DATA_BASE_URI + "&key=" + PREDICATES_STRING); - sptr settingDataObserver = - sptr(new SettingsDataEventMonitor(shared_from_this(), - SettingsDataMonitorType::USER_DEFINED_DEVICE_NAME_MONITOR)); - dataShareHelper->RegisterObserver(*uri, settingDataObserver); - - int32_t osAccountId = GetActiveOsAccountIds(); - if (osAccountId == ERR_DM_FAILED) { - LOGE("Get OsAccountId error"); - return; - } - std::string accountIdStr = std::to_string(osAccountId); - uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + - "?Proxy=true&key=" + USER_DEFINED_STRING); - - dataShareHelper->RegisterObserver(*uri, settingDataObserver); - dataShareHelper->Release(); - LOGI("register device name change cb success"); -} - -int32_t LocalDeviceNameMgr::QueryLocalDisplayName() -{ - auto dataShareHelper = GetDataShareHelper(); - if (dataShareHelper == nullptr) { - LOGE("dataShareHelper is null"); - return ERR_DM_FAILED; - } - std::string localDisplayName = ""; - int32_t ret = GetDisplayDeviceName(dataShareHelper, localDisplayName); - if (ret != DM_OK || localDisplayName.empty()) { - LOGE("get display device name failed"); - return ERR_DM_FAILED; - } - std::lock_guard lock(devNameMtx_); - localDisplayName_ = localDisplayName; - dataShareHelper->Release(); - LOGI("get display deviceName=%{public}s", localDisplayName.c_str()); - return DM_OK; -} - -void LocalDeviceNameMgr::RegisterDisplayNameChangeCb() -{ - auto dataShareHelper = GetDataShareHelper(); - if (dataShareHelper == nullptr) { - LOGE("dataShareHelper is null"); - return; - } - - int32_t osAccountId = GetActiveOsAccountIds(); - if (osAccountId == ERR_DM_FAILED) { - LOGE("Get OsAccountId error"); - return; - } - std::string accountIdStr = std::to_string(osAccountId); - auto uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + - "?Proxy=true&key=" + DISPLAY_DEVICE_NAME_STRING); - sptr settingDataObserver = - sptr(new SettingsDataEventMonitor(shared_from_this(), - SettingsDataMonitorType::DISPLAY_DEVICE_NAME_MONITOR)); - dataShareHelper->RegisterObserver(*uri, settingDataObserver); - dataShareHelper->Release(); - LOGI("register display device name change cb success"); -} - -std::string LocalDeviceNameMgr::GetLocalDisplayName() const -{ - std::lock_guard lock(devNameMtx_); - return localDisplayName_; -} - -std::string LocalDeviceNameMgr::GetLocalDeviceName() const -{ - std::lock_guard lock(devNameMtx_); - return localDeviceName_; -} -} // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file diff --git a/services/service/src/devicenamemgr/settings_data_event_monitor.cpp b/services/service/src/devicenamemgr/settings_data_event_monitor.cpp deleted file mode 100644 index 421acfc7b..000000000 --- a/services/service/src/devicenamemgr/settings_data_event_monitor.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "settings_data_event_monitor.h" - -#include "dm_log.h" - -namespace OHOS { -namespace DistributedHardware { -SettingsDataEventMonitor::SettingsDataEventMonitor(std::shared_ptr localDeviceNameMgr, - SettingsDataMonitorType monitorType) - : localDeviceNameMgrWPtr_(localDeviceNameMgr), monitorType_(monitorType) -{ - LOGI("Ctor SettingsDataEventMonitor, monitorType: %{public}d", (int32_t)monitorType); -} - -void SettingsDataEventMonitor::OnChange() -{ - if (localDeviceNameMgrWPtr_.expired()) { - LOGE("localDeviceNameMgrWPtr_ expired"); - return; - } - LOGI("Settings OnChange type: %{public}d", (int32_t)monitorType_); - std::shared_ptr localDevNameSPtr = localDeviceNameMgrWPtr_.lock(); - if (localDevNameSPtr == nullptr) { - LOGE("localDevNameSPtr is null!"); - return; - } - switch (monitorType_) { - case SettingsDataMonitorType::USER_DEFINED_DEVICE_NAME_MONITOR: - localDevNameSPtr->QueryLocalDeviceName(); - break; - case SettingsDataMonitorType::DISPLAY_DEVICE_NAME_MONITOR: - localDevNameSPtr->QueryLocalDisplayName(); - break; - default: - LOGE("unknwon monitor type"); - break; - } -} -} // DistributedHardware -} // OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 01683be73..3b3746bab 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -255,6 +255,11 @@ public: (void)deviceName; (void)code; } + + virtual std::string GetLocalDisplayDeviceNameForPrivacy() + { + return ""; + } }; } // namespace DistributedHardware } // namespace OHOS -- Gitee From 771cabacd2b7cf9262d0d4dabde2d06cd0a1c3ec Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Thu, 24 Apr 2025 20:55:53 +0800 Subject: [PATCH 2/5] moidyf nick name Signed-off-by: hwzhangchuang --- services/service/src/devicenamemgr/device_name_manager.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/service/src/devicenamemgr/device_name_manager.cpp b/services/service/src/devicenamemgr/device_name_manager.cpp index 87472bf13..d27a4dc4c 100644 --- a/services/service/src/devicenamemgr/device_name_manager.cpp +++ b/services/service/src/devicenamemgr/device_name_manager.cpp @@ -342,6 +342,10 @@ int32_t DeviceNameManager::GetLocalDisplayDeviceName(int32_t maxNamelength, std: std::string DeviceNameManager::GenLocalAnoyDeviceNameWithNickAndMarketName(const std::string &nickName, const std::string &marketName) { + if (nickName.empty()) { + return marketName; + } + std::string anoyNickName = AnoyPrivacyString(nickName); std::string nameSeparator = NAME_SEPARATOR_ZH; if (GetSystemLanguage() != LANGUAGE_ZH_HANS || GetSystemRegion() != LOCAL_ZH_HANS_CN) { -- Gitee From bbebe5c182bea48193b02e5b3c5de78425db22c1 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Fri, 25 Apr 2025 09:08:41 +0800 Subject: [PATCH 3/5] modify idx error Signed-off-by: hwzhangchuang --- services/service/src/devicenamemgr/device_name_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/src/devicenamemgr/device_name_manager.cpp b/services/service/src/devicenamemgr/device_name_manager.cpp index d27a4dc4c..170ae5951 100644 --- a/services/service/src/devicenamemgr/device_name_manager.cpp +++ b/services/service/src/devicenamemgr/device_name_manager.cpp @@ -463,7 +463,7 @@ std::string DeviceNameManager::AnoyPrivacyString(const std::string &str) return ""; } if (wholeCharVec.size() == NUM1) { - return wholeCharVec[1]; + return wholeCharVec[0]; } std::string res; -- Gitee From eec5989166e3c7fc8079a2ee21b379a8fed8e0df Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sat, 26 Apr 2025 15:53:11 +0800 Subject: [PATCH 4/5] recover full display name before save acl Signed-off-by: hwzhangchuang --- .../authentication_v2/dm_auth_message_processor.h | 3 +++ .../src/authentication_v2/auth_stages/auth_acl.cpp | 3 ++- .../authentication_v2/dm_auth_message_processor.cpp | 12 ++++++++---- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index b5338f243..557ae5bad 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -139,7 +139,10 @@ struct DmAccessControlTable { // Structure used for synchronizing ACL access // Attention: Modifying this structure requires updating the From/ToJson functions in dm_auth_message_processor.cpp. struct DmAccessToSync { + // the deviceName translate in 80/90 messages, cleaned the privacy info std::string deviceName; + // the device display name, which need save in DB + std::string deviceNameFull; // For A->B communication, whether it's the A end or B end, the Accesser object stores // the A end's deviceId, and the Accessee object stores the B end's deviceId std::string deviceId; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 7ef9fe1f7..3e9e17bb0 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -40,6 +40,7 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) // Synchronize the local SP information, the format is uncertain, not done for now context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_DATA_SYNC, context); + context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); LOGI("AuthSinkDataSyncState::Action ok"); return DM_OK; } @@ -58,7 +59,7 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) // Query the ACL of the sink end. Compare the ACLs at both ends. context->softbusConnector->SyncLocalAclListProcess({context->accesser.deviceId, context->accesser.userId}, {context->accessee.deviceId, context->accessee.userId}, context->accessee.aclStrList); - + context->accesser.deviceName = context->softbusConnector->GetLocalDeviceName(); // Save this acl SetAclInfo(context); context->authMessageProcessor->PutAccessControlList(context, context->accesser, context->accessee.deviceId); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index cf8d349fa..5f50b8b98 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -103,11 +103,11 @@ const char* TAG_DEVICE_TYPE = "DEVICETYPE"; constexpr int32_t DM_ULTRASONIC_FORWARD = 0; constexpr int32_t DM_ULTRASONIC_REVERSE = 1; -void ParseDmAccessToSync(const std::string &jsonString, DmAccess &access) +void ParseDmAccessToSync(const std::string &jsonString, DmAccess &access, bool isUseDeviceFullName) { JsonObject accessjson(jsonString); DmAccessToSync srcAccessToSync = accessjson.Get(); - access.deviceName = srcAccessToSync.deviceName; + access.deviceName = (isUseDeviceFullName ? srcAccessToSync.deviceNameFull : srcAccessToSync.deviceName); access.deviceId = srcAccessToSync.deviceId; access.userId = srcAccessToSync.userId; access.accountId = srcAccessToSync.accountId; @@ -779,13 +779,13 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr } std::string srcAccessStr = jsonObject[TAG_ACCESS].Get(); // Parse into access - ParseDmAccessToSync(srcAccessStr, accessTmp); + ParseDmAccessToSync(srcAccessStr, accessTmp, false); // check access validity if (!CheckAccessValidityAndAssign(context, access, accessTmp)) { LOGE("ParseSyncMessage CheckAccessValidityAndAssign error, data between two stages different, stop auth."); return ERR_DM_FAILED; } - ParseDmAccessToSync(srcAccessStr, access); + ParseDmAccessToSync(srcAccessStr, access, true); if (!jsonObject[TAG_ACL_CHECKSUM].IsString()) { // Re-parse the acl LOGE("ParseSyncMessage TAG_ACL_CHECKSUM error"); return ERR_DM_FAILED; @@ -1316,6 +1316,7 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrsoftbusConnector->GetLocalDeviceName(); accessToSync.deviceId = accessSide.deviceId; accessToSync.userId = accessSide.userId; accessToSync.accountId = accessSide.accountId; @@ -1323,6 +1324,7 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr Date: Sat, 26 Apr 2025 18:04:35 +0800 Subject: [PATCH 5/5] anoy deviceid, account and tokenId Signed-off-by: hwzhangchuang --- .../auth_stages/auth_confirm.cpp | 26 +++++------ .../auth_stages/auth_negotiate.cpp | 38 ++++++++-------- .../dm_auth_message_processor.cpp | 6 +-- .../src/authentication_v2/dm_auth_state.cpp | 4 +- utils/include/crypto/dm_crypto.h | 11 +++++ utils/src/crypto/dm_crypto.cpp | 44 ++++++++++++++++++- 6 files changed, 91 insertions(+), 38 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 1b47a17c1..e4f0045de 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -190,7 +190,7 @@ void AuthSrcConfirmState::GetSrcAclInfo(std::shared_ptr context, uint32_t bindLevel = DM_INVALIED_TYPE; for (const auto &item : profiles) { std::string trustDeviceId = item.GetTrustDeviceId(); - std::string trustDeviceIdHash = Crypto::Sha256(trustDeviceId); + std::string trustDeviceIdHash = Crypto::GetUdidHash(trustDeviceId); if ((trustDeviceIdHash != context->accessee.deviceIdHash && trustDeviceIdHash != context->accesser.deviceIdHash)) { LOGE("devId %{public}s hash %{public}s, accesser devId %{public}s.", GetAnonyString(trustDeviceId).c_str(), @@ -309,7 +309,7 @@ bool AuthSrcConfirmState::IdenticalAccountAclCompare(std::shared_ptraccesser.deviceId && accesser.GetAccesserUserId() == context->accesser.userId && - Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash; + Crypto::GetUdidHash(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash; } bool AuthSrcConfirmState::ShareAclCompare(std::shared_ptr context, @@ -318,7 +318,7 @@ bool AuthSrcConfirmState::ShareAclCompare(std::shared_ptr context LOGI("start."); return accesser.GetAccesserDeviceId() == context->accesser.deviceId && accesser.GetAccesserUserId() == context->accesser.userId && - Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash; + Crypto::GetUdidHash(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash; } bool AuthSrcConfirmState::Point2PointAclCompare(std::shared_ptr context, @@ -328,13 +328,13 @@ bool AuthSrcConfirmState::Point2PointAclCompare(std::shared_ptr c return (accesser.GetAccesserDeviceId() == context->accesser.deviceId && accesser.GetAccesserUserId() == context->accesser.userId && accesser.GetAccesserTokenId() == context->accesser.tokenId && - Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash && - Crypto::Sha256(std::to_string(accessee.GetAccesseeTokenId())) == context->accessee.tokenIdHash) || + Crypto::GetUdidHash(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash && + Crypto::GetTokenIdHash(std::to_string(accessee.GetAccesseeTokenId())) == context->accessee.tokenIdHash) || (accessee.GetAccesseeDeviceId() == context->accesser.deviceId && accessee.GetAccesseeUserId() == context->accesser.userId && accessee.GetAccesseeTokenId() == context->accesser.tokenId && - Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accessee.deviceIdHash && - Crypto::Sha256(std::to_string(accesser.GetAccesserTokenId())) == context->accessee.tokenIdHash); + Crypto::GetUdidHash(accesser.GetAccesserDeviceId()) == context->accessee.deviceIdHash && + Crypto::GetTokenIdHash(std::to_string(accesser.GetAccesserTokenId())) == context->accessee.tokenIdHash); } bool AuthSrcConfirmState::LnnAclCompare(std::shared_ptr context, @@ -346,8 +346,8 @@ bool AuthSrcConfirmState::LnnAclCompare(std::shared_ptr context, (accessee.GetAccesseeDeviceId() == context->accesser.deviceId && accessee.GetAccesseeUserId() == context->accesser.userId)) && accesser.GetAccesserTokenId() == 0 && accesser.GetAccesserBundleName() == "" && - (Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash || - Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accessee.deviceIdHash) && + (Crypto::GetUdidHash(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash || + Crypto::GetUdidHash(accesser.GetAccesserDeviceId()) == context->accessee.deviceIdHash) && accessee.GetAccesseeTokenId() == 0 && accessee.GetAccesseeBundleName() == ""; } @@ -361,14 +361,14 @@ void AuthSrcConfirmState::GetSrcCredentialInfo(std::shared_ptr co } // get share credential if (context->accesser.accountIdHash != context->accessee.accountIdHash && - context->accesser.accountIdHash != Crypto::Sha256("ohosAnonymousUid") && - context->accessee.accountIdHash != Crypto::Sha256("ohosAnonymousUid")) { + context->accesser.accountIdHash != Crypto::GetAccountIdHash16("ohosAnonymousUid") && + context->accessee.accountIdHash != Crypto::GetAccountIdHash16("ohosAnonymousUid")) { GetShareCredentialInfo(context, credInfo); GetP2PCredentialInfo(context, credInfo); } // get point_to_point credential - if (context->accesser.accountIdHash == Crypto::Sha256("ohosAnonymousUid") || - context->accessee.accountIdHash == Crypto::Sha256("ohosAnonymousUid")) { + if (context->accesser.accountIdHash == Crypto::GetAccountIdHash16("ohosAnonymousUid") || + context->accessee.accountIdHash == Crypto::GetAccountIdHash16("ohosAnonymousUid")) { GetP2PCredentialInfo(context, credInfo); } std::vector deleteCredInfo; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 2e8d3d892..76c6672ea 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -91,9 +91,9 @@ int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr cont context->accessee.dmVersion = ""; // Calculate the hash value - context->accesser.deviceIdHash = Crypto::Sha256(context->accesser.deviceId); - context->accesser.accountIdHash = Crypto::Sha256(context->accesser.accountId); - context->accesser.tokenIdHash = Crypto::Sha256(std::to_string(context->accesser.tokenId)); + context->accesser.deviceIdHash = Crypto::GetUdidHash(context->accesser.deviceId); + context->accesser.accountIdHash = Crypto::GetAccountIdHash16(context->accesser.accountId); + context->accesser.tokenIdHash = Crypto::GetTokenIdHash(std::to_string(context->accesser.tokenId)); // Create old message for compatible context->accesser.accountGroupIdHash = GetAccountGroupIdHash(context); @@ -123,7 +123,7 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.deviceId = std::string(localDeviceId); - context->accessee.deviceIdHash = Crypto::Sha256(context->accessee.deviceId); + context->accessee.deviceIdHash = Crypto::GetUdidHash(context->accessee.deviceId); // 2. Get userId context->accessee.userId = MultipleUserConnector::GetUserIdByDisplayId( @@ -135,7 +135,7 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context->accessee.userId); - context->accessee.accountIdHash = Crypto::Sha256(context->accessee.accountId); + context->accessee.accountIdHash = Crypto::GetAccountIdHash16(context->accessee.accountId); // 4. Get tokenId if (AppManager::GetInstance().GetNativeTokenIdByName(context->accessee.bundleName, @@ -151,7 +151,7 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.bundleName)) { context->accessee.bindLevel = DmRole::DM_ROLE_USER; } - context->accessee.tokenIdHash = Crypto::Sha256(std::to_string(context->accessee.tokenId)); + context->accessee.tokenIdHash = Crypto::GetTokenIdHash(std::to_string(context->accessee.tokenId)); context->accesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceIdHash, true); context->accessee.language = DmLanguageManager::GetInstance().GetSystemLanguage(); context->accessee.deviceName = context->listener->GetLocalDisplayDeviceNameForPrivacy(); @@ -290,7 +290,7 @@ void AuthSinkNegotiateStateMachine::GetSinkAclInfo(std::shared_ptraccesser.deviceIdHash && trustDeviceIdHash != context->accessee.deviceIdHash) { LOGE("devId %{public}s hash %{public}s, er devId %{public}s.", GetAnonyString(trustDeviceId).c_str(), @@ -410,7 +410,7 @@ bool AuthSinkNegotiateStateMachine::IdenticalAccountAclCompare(std::shared_ptraccessee.deviceId && accesser.GetAccesserUserId() == context->accessee.userId && - Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash; + Crypto::GetUdidHash(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash; } bool AuthSinkNegotiateStateMachine::ShareAclCompare(std::shared_ptr context, @@ -419,7 +419,7 @@ bool AuthSinkNegotiateStateMachine::ShareAclCompare(std::shared_ptraccessee.deviceId && accessee.GetAccesseeUserId() == context->accessee.userId && - Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash; + Crypto::GetUdidHash(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash; } bool AuthSinkNegotiateStateMachine::Point2PointAclCompare(std::shared_ptr context, @@ -429,13 +429,13 @@ bool AuthSinkNegotiateStateMachine::Point2PointAclCompare(std::shared_ptraccessee.deviceId && accessee.GetAccesseeUserId() == context->accessee.userId && accessee.GetAccesseeTokenId() == context->accessee.tokenId && - Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && - Crypto::Sha256(std::to_string(accesser.GetAccesserTokenId())) == context->accesser.tokenIdHash) || + Crypto::GetUdidHash(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && + Crypto::GetTokenIdHash(std::to_string(accesser.GetAccesserTokenId())) == context->accesser.tokenIdHash) || (accesser.GetAccesserDeviceId() == context->accessee.deviceId && accesser.GetAccesserUserId() == context->accessee.userId && accesser.GetAccesserTokenId() == context->accessee.tokenId && - Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash && - Crypto::Sha256(std::to_string(accessee.GetAccesseeTokenId())) == context->accesser.tokenIdHash); + Crypto::GetUdidHash(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash && + Crypto::GetTokenIdHash(std::to_string(accessee.GetAccesseeTokenId())) == context->accesser.tokenIdHash); } bool AuthSinkNegotiateStateMachine::LnnAclCompare(std::shared_ptr context, @@ -447,8 +447,8 @@ bool AuthSinkNegotiateStateMachine::LnnAclCompare(std::shared_ptr (accesser.GetAccesserDeviceId() == context->accessee.deviceId && accesser.GetAccesserUserId() == context->accessee.userId)) && accessee.GetAccesseeTokenId() == 0 && accessee.GetAccesseeBundleName() == "" && - (Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash || - Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash) && + (Crypto::GetUdidHash(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash || + Crypto::GetUdidHash(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash) && accesser.GetAccesserTokenId() == 0 && accesser.GetAccesserBundleName() == ""; } @@ -462,14 +462,14 @@ void AuthSinkNegotiateStateMachine::GetSinkCredentialInfo(std::shared_ptraccesser.accountIdHash != context->accessee.accountIdHash && - context->accesser.accountIdHash != Crypto::Sha256("ohosAnonymousUid") && - context->accessee.accountIdHash != Crypto::Sha256("ohosAnonymousUid")) { + context->accesser.accountIdHash != Crypto::GetAccountIdHash16("ohosAnonymousUid") && + context->accessee.accountIdHash != Crypto::GetAccountIdHash16("ohosAnonymousUid")) { GetShareCredentialInfo(context, credInfo); GetP2PCredentialInfo(context, credInfo); } // get point_to_point credential - if (context->accesser.accountIdHash == Crypto::Sha256("ohosAnonymousUid") || - context->accessee.accountIdHash == Crypto::Sha256("ohosAnonymousUid")) { + if (context->accesser.accountIdHash == Crypto::GetAccountIdHash16("ohosAnonymousUid") || + context->accessee.accountIdHash == Crypto::GetAccountIdHash16("ohosAnonymousUid")) { GetP2PCredentialInfo(context, credInfo); } std::vector deleteCredInfo; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 5f50b8b98..960ff1670 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -714,10 +714,10 @@ bool DmAuthMessageProcessor::CheckAccessValidityAndAssign(std::shared_ptr context, const } // tokenIdList = [srcTokenId, sinkTokenId] - std::string srcTokenIdHash = Crypto::Sha256(tokenList[0]); - std::string sinkTokenIdHash = Crypto::Sha256(tokenList[1]); + std::string srcTokenIdHash = Crypto::GetTokenIdHash(tokenList[0]); + std::string sinkTokenIdHash = Crypto::GetTokenIdHash(tokenList[1]); return ((srcTokenIdHash == context->accesser.tokenIdHash) && (sinkTokenIdHash == context->accessee.tokenIdHash)) || diff --git a/utils/include/crypto/dm_crypto.h b/utils/include/crypto/dm_crypto.h index bd4bbaa8c..53e3b3c97 100644 --- a/utils/include/crypto/dm_crypto.h +++ b/utils/include/crypto/dm_crypto.h @@ -36,14 +36,25 @@ public: bool isUpper = false); EXPORT static int32_t ConvertHexStringToBytes(unsigned char *outBuf, uint32_t outBufLen, const char *inBuf, uint32_t inLen); + // follow the dsoftbus udid hash policy, use the first 8 bytes of full udid hash, + // after convert to string, it it 16 bytes. EXPORT static int32_t GetUdidHash(const std::string &udid, unsigned char *udidHash); + EXPORT static std::string GetUdidHash(const std::string &udid); + // use the first 16 bytes of full tokenId hash + // after convert to string, it it 32 bytes. + EXPORT static std::string GetTokenIdHash(const std::string &tokenId); EXPORT static std::string GetGroupIdHash(const std::string &groupId); static int32_t GetSecRandom(uint8_t *out, size_t outLen); static std::string GetSecSalt(); static std::string GetHashWithSalt(const std::string &text, const std::string &salt); + // follow the dsoftbus accountid hash policy, use the first 3 bytes of full accountid hash, + // after convert to string, it it 6 bytes. EXPORT static int32_t GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash); + // use the first 16 bytes of full accountId hash + // after convert to string, it it 32 bytes. + EXPORT static std::string GetAccountIdHash16(const std::string &accountId); EXPORT static int32_t ConvertBytesToHexString(char *outBuf, uint32_t outBufLen, const unsigned char *inBuf, uint32_t inLen); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) diff --git a/utils/src/crypto/dm_crypto.cpp b/utils/src/crypto/dm_crypto.cpp index 015adfa62..708adc8ab 100644 --- a/utils/src/crypto/dm_crypto.cpp +++ b/utils/src/crypto/dm_crypto.cpp @@ -112,7 +112,7 @@ std::string Crypto::Sha256(const void *data, size_t size, bool isUpper) return ss.str(); } -int32_t Crypto::GetUdidHash(const std::string &udid, unsigned char *udidHash) +EXPORT int32_t Crypto::GetUdidHash(const std::string &udid, unsigned char *udidHash) { unsigned char hash[SHA256_DIGEST_LENGTH] = ""; DmGenerateStrHash(udid.data(), udid.size(), hash, SHA256_DIGEST_LENGTH, 0); @@ -124,6 +124,34 @@ int32_t Crypto::GetUdidHash(const std::string &udid, unsigned char *udidHash) return DM_OK; } +EXPORT std::string Crypto::GetUdidHash(const std::string &udid) +{ + unsigned char hash[SHA256_DIGEST_LENGTH] = ""; + char udidHash[DM_MAX_DEVICE_ID_LEN] = {0}; + DmGenerateStrHash(udid.data(), udid.size(), hash, SHA256_DIGEST_LENGTH, 0); + if (ConvertBytesToHexString(reinterpret_cast(udidHash), SHORT_DEVICE_ID_HASH_LENGTH + 1, + reinterpret_cast(hash), SHORT_DEVICE_ID_HASH_LENGTH / HEX_TO_UINT8) != DM_OK) { + LOGE("ConvertBytesToHexString failed."); + return ""; + } + std::string udidHashStr = std::string(udidHash); + return udidHashStr; +} + +EXPORT std::string Crypto::GetTokenIdHash(const std::string &tokenId) +{ + unsigned char hash[SHA256_DIGEST_LENGTH] = ""; + char idHash[DM_MAX_DEVICE_ID_LEN] = {0}; + DmGenerateStrHash(tokenId.data(), tokenId.size(), hash, SHA256_DIGEST_LENGTH, 0); + if (ConvertBytesToHexString(reinterpret_cast(idHash), SHA256_DIGEST_LENGTH + 1, + reinterpret_cast(hash), SHA256_DIGEST_LENGTH / HEX_TO_UINT8) != DM_OK) { + LOGE("ConvertBytesToHexString failed."); + return ""; + } + std::string tokenIdHash = std::string(idHash); + return tokenIdHash; +} + EXPORT int32_t Crypto::ConvertHexStringToBytes(unsigned char *outBuf, uint32_t outBufLen, const char *inBuf, uint32_t inLen) { @@ -224,6 +252,20 @@ EXPORT int32_t Crypto::GetAccountIdHash(const std::string &accountId, return DM_OK; } +EXPORT std::string Crypto::GetAccountIdHash16(const std::string &accountId) +{ + unsigned char hash[SHA256_DIGEST_LENGTH] = ""; + char accountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + DmGenerateStrHash(accountId.data(), accountId.size(), hash, SHA256_DIGEST_LENGTH, 0); + if (ConvertBytesToHexString(reinterpret_cast(accountIdHash), SHA256_DIGEST_LENGTH + 1, + reinterpret_cast(hash), SHA256_DIGEST_LENGTH / HEX_TO_UINT8) != DM_OK) { + LOGE("ConvertBytesToHexString failed."); + return ""; + } + std::string accountHashStr = std::string(accountIdHash); + return accountHashStr; +} + #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) EXPORT int32_t Crypto::ConvertUdidHashToAnoyAndSave(const std::string &appId, const std::string &udidHash, DmKVValue &kvValue) -- Gitee