From a96dc5e32f0d78f65cfc78d8923c1f6d2acd63da Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sun, 6 Apr 2025 11:51:24 +0800 Subject: [PATCH 1/8] add service code Signed-off-by: hwzhangchuang --- services/implementation/BUILD.gn | 15 + .../include/ability/dm_dialog_manager.h | 5 + .../authentication/auth_message_processor.h | 11 - .../include/authentication/dm_auth_manager.h | 11 +- .../include/authentication_v2/auth_manager.h | 207 +++ .../authentication_v2/dm_auth_context.h | 243 +++ .../authentication_v2/dm_auth_manager_base.h | 213 +++ .../dm_auth_message_processor.h | 332 ++++ .../include/authentication_v2/dm_auth_state.h | 445 ++++++ .../authentication_v2/dm_auth_state_machine.h | 118 ++ .../authentication_v2/dm_negotiate_process.h | 191 +++ .../include/cryptomgr/crypto_mgr.h | 1 + .../hichain/hichain_auth_connector.h | 19 + .../dependency/hichain/hichain_connector.h | 2 +- .../hichain/hichain_connector_callback.h | 3 +- .../dependency/softbus/softbus_connector.h | 9 +- .../dependency/softbus/softbus_session.h | 2 - .../include/device_manager_service_impl.h | 93 +- .../device_manager_service_impl_lite.h | 4 +- .../ability/standard/dm_dialog_manager.cpp | 49 +- .../authentication/auth_message_processor.cpp | 11 - .../src/authentication/dm_auth_manager.cpp | 149 +- .../src/authentication_v2/auth_manager.cpp | 1047 ++++++++++++ .../auth_stages/auth_acl.cpp | 156 ++ .../auth_stages/auth_confirm.cpp | 738 +++++++++ .../auth_stages/auth_credential.cpp | 529 +++++++ .../auth_stages/auth_negotiate.cpp | 542 +++++++ .../auth_stages/auth_pin_auth.cpp | 607 +++++++ .../src/authentication_v2/dm_auth_context.cpp | 90 ++ .../dm_auth_manager_base.cpp | 419 +++++ .../dm_auth_message_processor.cpp | 1406 +++++++++++++++++ .../src/authentication_v2/dm_auth_state.cpp | 296 ++++ .../dm_auth_state_machine.cpp | 345 ++++ .../dm_negotiate_process.cpp | 285 ++++ .../src/cryptomgr/crypto_mgr.cpp | 7 + .../hichain/hichain_auth_connector.cpp | 280 +++- .../dependency/softbus/softbus_connector.cpp | 129 +- .../dependency/softbus/softbus_session.cpp | 94 +- .../src/device_manager_service_impl.cpp | 1150 +++++++++++++- .../src/device_manager_service_impl_lite.cpp | 9 + .../include/idevice_manager_service_impl.h | 2 + .../relationship_sync_mgr.h | 2 + .../service/src/device_manager_service.cpp | 8 +- .../relationship_sync_mgr.cpp | 25 +- 44 files changed, 9971 insertions(+), 328 deletions(-) create mode 100644 services/implementation/include/authentication_v2/auth_manager.h create mode 100644 services/implementation/include/authentication_v2/dm_auth_context.h create mode 100644 services/implementation/include/authentication_v2/dm_auth_manager_base.h create mode 100644 services/implementation/include/authentication_v2/dm_auth_message_processor.h create mode 100644 services/implementation/include/authentication_v2/dm_auth_state.h create mode 100644 services/implementation/include/authentication_v2/dm_auth_state_machine.h create mode 100644 services/implementation/include/authentication_v2/dm_negotiate_process.h create mode 100644 services/implementation/src/authentication_v2/auth_manager.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp create mode 100644 services/implementation/src/authentication_v2/dm_auth_context.cpp create mode 100644 services/implementation/src/authentication_v2/dm_auth_manager_base.cpp create mode 100644 services/implementation/src/authentication_v2/dm_auth_message_processor.cpp create mode 100644 services/implementation/src/authentication_v2/dm_auth_state.cpp create mode 100644 services/implementation/src/authentication_v2/dm_auth_state_machine.cpp create mode 100644 services/implementation/src/authentication_v2/dm_negotiate_process.cpp diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index de3ddcad6..baf252972 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -115,6 +115,7 @@ if (defined(ohos_lite)) { "include/config", "include/adapter", "include/authentication", + "include/authentication_v2", "include/authentication/showconfirm/standard", "include/ability", "include/credential", @@ -182,6 +183,18 @@ if (defined(ohos_lite)) { "src/authentication/auth_ui_state_manager.cpp", "src/authentication/dm_auth_manager.cpp", "src/authentication/showconfirm/standard/show_confirm.cpp", + "src/authentication_v2/auth_manager.cpp", + "src/authentication_v2/auth_stages/auth_acl.cpp", + "src/authentication_v2/auth_stages/auth_confirm.cpp", + "src/authentication_v2/auth_stages/auth_credential.cpp", + "src/authentication_v2/auth_stages/auth_negotiate.cpp", + "src/authentication_v2/auth_stages/auth_pin_auth.cpp", + "src/authentication_v2/dm_auth_context.cpp", + "src/authentication_v2/dm_auth_manager_base.cpp", + "src/authentication_v2/dm_auth_message_processor.cpp", + "src/authentication_v2/dm_auth_state.cpp", + "src/authentication_v2/dm_auth_state_machine.cpp", + "src/authentication_v2/dm_negotiate_process.cpp", "src/config/dm_config_manager.cpp", "src/credential/dm_credential_manager.cpp", "src/cryptomgr/crypto_mgr.cpp", @@ -236,8 +249,10 @@ if (defined(ohos_lite)) { "mbedtls:mbedtls_shared", "openssl:libcrypto_shared", "os_account:libaccountkits", + "os_account:os_account_innerkits", "resource_management:resmgr_napi_core", "samgr:samgr_proxy", + "zlib:shared_libz", ] if (support_screenlock && device_manager_feature_product == "default") { diff --git a/services/implementation/include/ability/dm_dialog_manager.h b/services/implementation/include/ability/dm_dialog_manager.h index 1a42ff984..1ac717de7 100644 --- a/services/implementation/include/ability/dm_dialog_manager.h +++ b/services/implementation/include/ability/dm_dialog_manager.h @@ -77,6 +77,10 @@ public: { return hostPkgLabel_; } + static uint64_t GetTokenId() + { + return tokenId_; + } private: DmDialogManager(); ~DmDialogManager(); @@ -98,6 +102,7 @@ private: static std::string customDescriptionStr_; static std::string pinCode_; static std::string hostPkgLabel_; + static uint64_t tokenId_; static int32_t deviceType_; static std::atomic isConnectSystemUI_; static sptr dialogConnectionCallback_; diff --git a/services/implementation/include/authentication/auth_message_processor.h b/services/implementation/include/authentication/auth_message_processor.h index dde7dbf83..2c34222d5 100644 --- a/services/implementation/include/authentication/auth_message_processor.h +++ b/services/implementation/include/authentication/auth_message_processor.h @@ -27,7 +27,6 @@ namespace OHOS { namespace DistributedHardware { -extern const char* TAG_REPLY; extern const char* TAG_NET_ID; extern const char* TAG_TARGET; extern const char* TAG_APP_OPERATION; @@ -48,35 +47,25 @@ extern const char* TAG_CRYPTO_NAME; extern const char* TAG_CRYPTO_VERSION; extern const char* TAG_IDENTICAL_ACCOUNT; extern const char* TAG_ACCOUNT_GROUPID; -extern const char* APP_THUMBNAIL; extern const char* QR_CODE_KEY; extern const char* TAG_AUTH_TOKEN; extern const char* NFC_CODE_KEY; extern const char* OLD_VERSION_ACCOUNT; -extern const char* TAG_AUTH_FINISH; extern const char* TAG_HAVE_CREDENTIAL; extern const char* TAG_PUBLICKEY; extern const char* TAG_SESSIONKEY; -extern const char* TAG_BIND_LEVEL; -extern const char* TAG_LOCAL_USERID; extern const char* TAG_BIND_TYPE_SIZE; extern const char* TAG_ISONLINE; extern const char* TAG_AUTHED; extern const char* TAG_LOCAL_ACCOUNTID; -extern const char* TAG_DMVERSION; extern const char* TAG_HOST_PKGNAME; extern const char* TAG_TOKENID; extern const char* TAG_HAVECREDENTIAL; extern const char* TAG_CONFIRM_OPERATION; -extern const char* TAG_DATA; -extern const char* TAG_DATA_LEN; extern const char* TAG_IMPORT_AUTH_CODE; extern const char* TAG_HOST_PKGLABEL; -extern const char* TAG_EDITION; -extern const char* TAG_BUNDLE_NAME; extern const char* TAG_CRYPTIC_MSG; -extern const char* TAG_PEER_BUNDLE_NAME; extern const char* TAG_REMOTE_DEVICE_NAME; extern const char* TAG_SESSIONKEY_ID; diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 3dee55dac..f4247450a 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -28,6 +28,7 @@ #include "deviceprofile_connector.h" #include "dm_ability_manager.h" #include "dm_adapter_manager.h" +#include "dm_auth_manager_base.h" #include "dm_constants.h" #include "dm_device_info.h" #include "dm_timer.h" @@ -203,10 +204,7 @@ typedef struct DmAuthResponseContext { class AuthMessageProcessor; -class DmAuthManager final : public ISoftbusSessionCallback, - public ISoftbusConnectorCallback, - public IHiChainConnectorCallback, - public IDmDeviceAuthCallback, +class DmAuthManager final : public AuthManagerBase, public std::enable_shared_from_this { public: DmAuthManager(std::shared_ptr softbusConnector, @@ -483,7 +481,7 @@ public: * @tc.type: FUNC */ int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam); + const std::map &bindParam, int sessionId, int64_t logicalSessionId); void HandleSessionHeartbeat(std::string name); @@ -546,6 +544,7 @@ public: void AuthDeviceError(int64_t requestId, int32_t errorCode); void GetRemoteDeviceId(std::string &deviceId); void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen); + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams); int32_t GetSessionKeyIdSync(int64_t requestId); void OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message); void OnScreenLocked(); @@ -578,7 +577,6 @@ private: void SrcAuthenticateFinish(); std::string GetBundleLable(const std::string &bundleName); bool IsScreenLocked(); - std::string ConvertSrcVersion(const std::string &version, const std::string &edition); std::string ConvertSinkVersion(const std::string &version); void NegotiateRespMsg(const std::string &version); void SetAuthType(int32_t authType); @@ -597,6 +595,7 @@ private: void ProcessReqPublicKey(); int32_t GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId); bool CheckBindLevel(const JsonItemObject &jsonObj, const std::string &key, int32_t &bindLevel); + int32_t ProcessPinCode(const std::string &jsonStr); private: std::shared_ptr softbusConnector_; diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h new file mode 100644 index 000000000..016d2877d --- /dev/null +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -0,0 +1,207 @@ +/* + * Copyright (c) 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. + */ + +#ifndef OHOS_DM_AUTH_MANAGER_V2_H +#define OHOS_DM_AUTH_MANAGER_V2_H + +#include + +#include "auth_ui_state_manager.h" +#include "dm_auth_manager_base.h" +#include "hichain_auth_connector.h" +#include "hichain_connector.h" +#include "json_object.h" +#include "softbus_connector.h" +#include "softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { +struct DmAuthContext; + +class AuthManager : public AuthManagerBase, + public std::enable_shared_from_this { +public: + AuthManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + virtual ~AuthManager(); + + // External API begin + /** + * @tc.name: DmAuthManager::OnUserOperation + * @tc.desc: User Operation of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + virtual int32_t OnUserOperation(int32_t action, const std::string ¶ms) = 0; + + /** + * @tc.name: AuthManager::GeneratePincode + * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t BindTarget(const std::string &sessionName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, int64_t logicalSessionId); + + /** + * @tc.name: AuthManager::OnUserOperation + * @tc.desc: User Operation of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t GeneratePincode(); + + /** + * @tc.name: AuthManager::ImportAuthCode + * @tc.desc: Import auth code + * @tc.type: FUNC + */ + int32_t ImportAuthCode(const std::string &sessionName, const std::string &authCode); + + /** + * @tc.name: AuthManager::RegisterUiStateCallback + * @tc.desc: Register ui state callback + * @tc.type: FUNC + */ + int32_t RegisterUiStateCallback(const std::string sessionName); + + /** + * @tc.name: AuthManager::UnRegisterUiStateCallback + * @tc.desc: Unregister ui state callback + * @tc.type: FUNC + */ + int32_t UnRegisterUiStateCallback(const std::string sessionName); + + /** + * @tc.name: AuthManager::UnAuthenticateDevice + * @tc.desc: UnAuthenticate Device of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t UnAuthenticateDevice(const std::string &sessionName, const std::string &udid, int32_t bindLevel); + + /** + * @brief UnBind device. + * @param sessionName package name. + * @param deviceId device id. + * @return Return 0 if success. + */ + int32_t UnBindDevice(const std::string &sessionName, const std::string &udid, + int32_t bindLevel, const std::string &extra); + + void HandleDeviceNotTrust(const std::string &udid); + + int32_t RegisterAuthenticationType(int32_t authenticationType); + void OnScreenLocked(); + int32_t StopAuthenticateDevice(const std::string &sessionName); + // External API begin end + + // Internal API begin + void SetAuthContext(std::shared_ptr context); + std::shared_ptr GetAuthContext(); + static bool IsHmlSessionType(const std::string &sessionType); + int32_t GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId); + void GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam); + void SetBindTargetParams(const PeerTargetId &targetId); + int32_t GetReason(); + + // Extract the local ACL for message parsing and bus usage. + int32_t GetAclListStr(std::string &aclList); + // Internal API end + + void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); + +protected: + std::shared_ptr context_; + std::map bindParam_; + PeerTargetId targetId_; + + int32_t GetPinCode(int32_t &code); + void GetRemoteDeviceId(std::string &deviceId); +private: + int32_t ParseAuthType(const std::map &bindParam, int32_t &authType); + void ParseHmlInfoInJsonObject(const JsonObject &jsonObject); + void ParseJsonObject(const JsonObject &jsonObject); + void GetAuthParam(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); + std::string GetBundleName(const JsonObject &jsonObject); + void SetAuthType(int32_t authType); + bool IsAuthTypeSupported(const int32_t &authType); + bool IsAuthCodeReady(const std::string &sessionName); + int32_t CheckAuthParamVaild(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); + void InitAuthState(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); + int32_t AuthenticateDevice(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); +}; + +class AuthSrcManager : public AuthManager { +public: + AuthSrcManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + virtual ~AuthSrcManager() override = default; + + // External API begin + int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; + // External API end + + // IDmDeviceAuthCallback implement begin + bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; + void AuthDeviceError(int64_t requestId, int32_t errorCode) override; + void AuthDeviceFinish(int64_t requestId) override; + void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) override; + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override; + // IDmDeviceAuthCallback implement end + + // ISoftbusSessionCallback implement begin + void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) override; + void OnSessionClosed(int32_t sessionId) override; + void OnDataReceived(int32_t sessionId, std::string message) override; + + bool GetIsCryptoSupport() override; + void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override; + // ISoftbusSessionCallback implement end +}; + +class AuthSinkManager : public AuthManager { +public: + AuthSinkManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + virtual ~AuthSinkManager() override = default; + + // External API begin + int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; + // External API end + + // IDmDeviceAuthCallback implement begin + bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; + void AuthDeviceError(int64_t requestId, int32_t errorCode) override; + void AuthDeviceFinish(int64_t requestId) override; + void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) override; + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override; + // IDmDeviceAuthCallback implement end + + // ISoftbusSessionCallback implement begin + void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) override; + void OnSessionClosed(int32_t sessionId) override; + void OnDataReceived(int32_t sessionId, std::string message) override; + bool GetIsCryptoSupport() override; + void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override; + // ISoftbusSessionCallback implement end +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MANAGER_V2_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h new file mode 100644 index 000000000..906248ff6 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -0,0 +1,243 @@ +/* + * Copyright (c) 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. + */ + +#ifndef OHOS_DM_AUTH_CONTEXT_V2_H +#define OHOS_DM_AUTH_CONTEXT_V2_H +#include +#include + +#include "access_control_profile.h" +#include "authentication.h" +#include "auth_ui_state_manager.h" +#include "dm_ability_manager.h" +#include "dm_anonymous.h" +#include "dm_auth_message_processor.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "dm_timer.h" +#include "hichain_auth_connector.h" +#include "hichain_connector.h" +#include "softbus_connector.h" +#include "softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { + +class DmAuthStateMachine; +class DmAuthMessageProcessor; + +using CleanNotifyCallback = std::function; + +// PIN Code Authentication Type +enum DmAuthType : int32_t { + AUTH_TYPE_CRE = 0, + AUTH_TYPE_PIN, // Input PIN code + AUTH_TYPE_QR_CODE, // Not used in the new protocol + AUTH_TYPE_NFC, + AUTH_TYPE_NO_INTER_ACTION, // Not used in the new protocol + AUTH_TYPE_IMPORT_AUTH_CODE, // Import PIN code + AUTH_TYPE_UNKNOW, // Not used in the new protocol + AUTH_TYPE_PIN_ULTRASONIC, // Ultrasonic PIN code +}; + +enum DmAuthDirection { + DM_AUTH_SOURCE = 0, + DM_AUTH_SINK, +}; + +enum DmBindType { + DM_AUTH_USERID = 1, + DM_AUTH_SYSTEM_SERVICE, + DM_AUTH_APP_SERVICE, + DM_AUTH_DEVICEID, +}; + +enum DmAuthSide { + DM_AUTH_LOCAL_SIDE = 0, + DM_AUTH_REMOTE_SIDE, +}; + +enum DmAuthScope { + DM_AUTH_SCOPE_DEVICE = 1, + DM_AUTH_SCOPE_USER, + DM_AUTH_SCOPE_APP, +}; + +enum DmRole { + DM_ROLE_UNKNOWN = 0, + DM_ROLE_DEVICE = 1, + DM_ROLE_USER = 1, + DM_ROLE_SA, + DM_ROLE_FA, +}; + +enum { + DM_UNKNOWN_TYPE = 0, + DM_SAME_ACCOUNT_TYPE = 1, + DM_SHARE_TYPE = 2, + DM_POINT_TO_POINT_TYPE = 256, + DM_SAME_GROUP_TYPE = 3, +}; + +// Used for one-touch pairing +struct DmPeerTargetAddress { + // directly establish a Bluetooth connection + std::string peerBrMacAddress; + std::string peerBleMacAddress; + std::string peerWifiMacAddress; + std::string peerActionMacAddress; + + std::string peerWifiChannel; + std::string peerWifiIp; + uint16_t peerWifiPort; +}; + +struct DmPeerTarget { + DmBindType peerType; + std::string peerDeviceId; + int64_t peerServiceId; + int64_t peerSaTokenId; + std::string peerBundleName; + DmPeerTargetAddress peerTargetAddress; +}; + +struct DmAccess { + std::string deviceName; + int32_t deviceType; // Device types such as PC, mobile, watch, large screen, etc. + std::string deviceId; + std::string deviceIdHash; + std::string addr; + int32_t userId; + std::string userIdHash; + int32_t displayId{0}; // Logical screen ID, used for query userId + std::string accountId; + std::string accountIdHash; + int64_t tokenId; + std::string tokenIdHash; + std::string networkId; + std::string bundleName; // Stores the PacketName + std::string language; + int64_t serviceId; // Reserved field, to be used in HM 6.0 + std::string accesserHapSignature; + int32_t bindLevel; + int32_t lnnBindType; + int32_t transmitBindType; + std::string lnnCredentialId; // User-level credential ID + std::string transmitCredentialId; // Application-level credential ID + std::string lnnPublicKey; // User-level public key + std::string transmitPublicKey; // Application-level public key + std::vector bindType; // such as DM_AUTH_CREDENTIAL_ACCOUNT_RELATED + std::string publicKey; + int32_t status; // Indicates whether the service is in the foreground or background + int32_t sessionKeyId; // Used as key delivery material, retrieves the SK from the bus + int32_t transmitSessionKeyId; // Permanent application SKID on this end, returned by DP for ACL updates and aging + int32_t lnnSessionKeyId; // Permanent user SKID on this end, returned by DP for ACL updates and aging + int64_t transmitSkTimeStamp; // Used for aging, time is 2 days, application-level credential timestamp + int64_t lnnSkTimeStamp; // Used for aging, time is 2 days, user-level credential timestamp + int64_t skTimeStamp; // Used for aging, time is 2 days + bool isAuthed; + bool isOnline; + bool isGenerateLnnCredential{true}; + bool isPutLnnAcl{true}; + std::string dmVersion; + std::string edition; // Used for compatibility before version 5.1.0, assists in version negotiation + std::string aclList; // Trust relationship list, used for data aging, KV format + std::string credTypeList; + std::vector accesserStrList; + std::vector accesseeStrList; + std::map credentialInfos; // map: , cred is string tranformed by json + std::map aclProfiles; + std::string extraInfo; // Expandable field, JSON format, KV structure +}; + +struct DmAuthContext { + bool isOnline; + int64_t logicalSessionId; + DmMessageType msgType; + int32_t sessionId; + int64_t requestId; // HiChain authentication ID + int32_t authBoxType{1}; // Authentication box type + UiAction pinInputResult; + // Authorization result (using 0, 1, 6, representing single use, cancel, and always trust, enum UiAction) + UiAction authResult{UiAction::USER_OPERATION_TYPE_ALLOW_AUTH}; + DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // PIN code, ultrasonic PIN code, imported PIN code + std::vector authTypeList; + uint32_t currentAuthTypeIdx{0}; + int32_t inputPinAuthFailTimes{0}; // Number of failed PIN authentication attempts, exceeding 3 results in failure + int32_t pinCode{INVALID_PINCODE}; + bool serviceInfoFound{false}; + // Link delay release time, does not automatically disconnect after + // authorization (used for specific business needs), reserved field + int32_t connDelayCloseTime; + int32_t reason{DM_OK}; + int32_t reply; + int32_t state; + int32_t hmlActionId = 0; + bool normalFinishAuth; + bool authenticating; // Indicator whether authentication is in progress + bool isFinished{false}; + bool isAppCredentialVerified{false}; // Whether the application credential has been verified + bool hmlEnable160M{false}; + std::string sessionName; // Business-provided identifier, custom-defined by business, carries risk of spoofing + std::string pkgLabel; + std::string importCodeBundleName; // Bundle name for imported PIN code + std::string appThumbnail; // Application thumbnail + // Description of the operation this binding is used for, displayed in authorization dialog + std::string appOperation; + // Custom business field, provides detailed information to the user about this binding operation + std::string customData; + std::string connSessionType; + std::string extraInfo; // Expandable field, key-value structure + DmAuthDirection direction; // Indicator of authentication direction + ProcessInfo processInfo; + DmPeerTarget peerTarget; + DmAccess accesser; + DmAccess accessee; + std::multimap proxy; // Multimap where the key is the accessor and the value is the accesssee + + std::shared_ptr authStateMachine; + std::shared_ptr authUiStateMgr; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authMessageProcessor; + std::shared_ptr softbusConnector; + std::shared_ptr listener; + std::shared_ptr authPtr; // Pointer to authentication interface + std::shared_ptr timer; + std::string transmitData; // Data returned from onTrasmit function + std::string importSessionName = ""; + std::string importAuthCode = ""; + std::map> authenticationMap; + PeerTargetId peerTargetId; + bool pinNegotiateStarted{false}; + bool isAuthenticateDevice{false}; // Whether device authentication is in progress + bool needBind{true}; + bool needAgreeCredential{true}; + bool needAuth{true}; + + CleanNotifyCallback cleanNotifyCallback; + + std::string GetDeviceId(DmAuthSide side); + int32_t GetUserId(DmAuthSide side); + std::string GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope); + std::string GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope); + void SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId); + void SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey); + std::string GetAccountId(DmAuthSide side); + uint32_t GetBindType(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_CONTEXT_V2_H diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h new file mode 100644 index 000000000..a8879da11 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -0,0 +1,213 @@ +/* + * Copyright (c) 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. + */ + +#ifndef OHOS_DM_AUTH_ADAPTER_V2_H +#define OHOS_DM_AUTH_ADAPTER_V2_H + +#include +#include +#include +#include + +#include "softbus_session_callback.h" +#include "hichain_connector_callback.h" +#include "hichain_connector_callback.h" +#include "auth_request_state.h" +#include "auth_response_state.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { + +extern const char* DM_VERSION_5_0_1; +extern const char* DM_VERSION_5_0_2; +extern const char* DM_VERSION_5_0_3; +extern const char* DM_VERSION_5_0_4; +extern const char* DM_VERSION_5_0_5; +extern const char* DM_VERSION_5_1_0; +extern const char* DM_VERSION_5_0_OLD_MAX; // Estimated highest version number of the old version + +extern const char* TAG_DMVERSION; +extern const char* TAG_EDITION; +extern const char* TAG_DATA; +extern const char* TAG_DATA_LEN; +extern const char* TAG_BUNDLE_NAME; +extern const char* TAG_PEER_BUNDLE_NAME; +extern const char* TAG_BIND_LEVEL; +extern const char* TAG_REPLY; +extern const char* TAG_APP_THUMBNAIL2; // Naming Add 2 to resolve conflicts with TAG_APP_THUMBNAIL +extern const char* TAG_AUTH_FINISH; +extern const char* TAG_LOCAL_USERID; + +extern const char* APP_OPERATION_KEY; +extern const char* TARGET_PKG_NAME_KEY; +extern const char* CUSTOM_DESCRIPTION_KEY; +extern const char* CANCEL_DISPLAY_KEY; +extern const char* BUNDLE_NAME_KEY; + +extern const char* AUTHENTICATE_TIMEOUT_TASK; +extern const char* NEGOTIATE_TIMEOUT_TASK; +extern const char* CONFIRM_TIMEOUT_TASK; +extern const char* INPUT_TIMEOUT_TASK; +extern const char* SESSION_HEARTBEAT_TIMEOUT_TASK; +extern const char* WAIT_REQUEST_TIMEOUT_TASK; +extern const char* AUTH_DEVICE_TIMEOUT_TASK; +extern const char* WAIT_PIN_AUTH_TIMEOUT_TASK; +extern const char* WAIT_NEGOTIATE_TIMEOUT_TASK; +extern const char* ADD_TIMEOUT_TASK; +extern const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK; +extern const char* CLOSE_SESSION_TASK_SEPARATOR; + +extern const int32_t AUTHENTICATE_TIMEOUT; +extern const int32_t CONFIRM_TIMEOUT; +extern const int32_t NEGOTIATE_TIMEOUT; +extern const int32_t INPUT_TIMEOUT; +extern const int32_t ADD_TIMEOUT; +extern const int32_t WAIT_NEGOTIATE_TIMEOUT; +extern const int32_t WAIT_REQUEST_TIMEOUT; +extern const int32_t CLONE_AUTHENTICATE_TIMEOUT; +extern const int32_t CLONE_CONFIRM_TIMEOUT; +extern const int32_t CLONE_NEGOTIATE_TIMEOUT; +extern const int32_t CLONE_ADD_TIMEOUT; +extern const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT; +extern const int32_t CLONE_WAIT_REQUEST_TIMEOUT; +extern const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT; +extern const int32_t CLONE_PIN_AUTH_TIMEOUT; +extern const int32_t HML_SESSION_TIMEOUT; +extern const int32_t SESSION_HEARTBEAT_TIMEOUT; +extern const int32_t PIN_AUTH_TIMEOUT; +extern const int32_t EVENT_TIMEOUT; + +extern const int32_t DM_AUTH_TYPE_MAX; +extern const int32_t DM_AUTH_TYPE_MIN; +extern const int32_t MIN_PIN_TOKEN; +extern const int32_t MAX_PIN_TOKEN; + +using CleanNotifyCallback = std::function; + +class AuthManagerBase : public ISoftbusSessionCallback, + public IHiChainConnectorCallback, + public IDmDeviceAuthCallback { +public: + virtual int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, + const std::string &extra); + + virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); + + virtual int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra); + + virtual void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result); + + virtual void OnSessionClosed(const int32_t sessionId); + + virtual void OnDataReceived(const int32_t sessionId, const std::string message); + + virtual void OnGroupCreated(int64_t requestId, const std::string &groupId); + + virtual void OnMemberJoin(int64_t requestId, int32_t status); + + virtual int32_t EstablishAuthChannel(const std::string &deviceId); + + virtual void StartNegotiate(const int32_t &sessionId); + + virtual void RespNegotiate(const int32_t &sessionId); + + virtual void SendAuthRequest(const int32_t &sessionId); + + virtual int32_t StartAuthProcess(const int32_t &action); + + virtual void StartRespAuthProcess(); + + virtual int32_t CreateGroup(); + + virtual int32_t ProcessPincode(int32_t pinCode); + + virtual std::string GetConnectAddr(std::string deviceId); + + virtual int32_t JoinNetwork(); + + virtual void AuthenticateFinish(); + + virtual bool GetIsCryptoSupport(); + + virtual int32_t SetAuthRequestState(std::shared_ptr authRequestState); + + virtual int32_t SetAuthResponseState(std::shared_ptr authResponseState); + + virtual int32_t GetPinCode(int32_t &code); + + virtual std::string GenerateGroupName(); + + virtual void HandleAuthenticateTimeout(std::string name); + + virtual int32_t GeneratePincode(); + + virtual void ShowConfigDialog(); + + virtual void ShowAuthInfoDialog(bool authDeviceError = false); + + virtual void ShowStartAuthDialog(); + + virtual int32_t OnUserOperation(int32_t action, const std::string ¶ms); + + virtual int32_t SetPageId(int32_t pageId); + + virtual int32_t SetReasonAndFinish(int32_t reason, int32_t state); + + virtual bool IsIdenticalAccount(); + + virtual int32_t RegisterUiStateCallback(const std::string pkgName); + + virtual int32_t UnRegisterUiStateCallback(const std::string pkgName); + + virtual int32_t ImportAuthCode(const std::string &pkgName, const std::string &authCode); + + virtual int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, int64_t logicalSessionId); + + virtual int32_t RegisterAuthenticationType(int32_t authenticationType); + + virtual int32_t StopAuthenticateDevice(const std::string &pkgName); + + virtual void OnScreenLocked() = 0; + + virtual void HandleDeviceNotTrust(const std::string &udid) = 0; + + virtual int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); + + // New interface added in version 5.1.0 + virtual int32_t GetReason(); + // When switching from the new protocol to the old protocol, the previous parameters + // need to be obtained for use by the old protocol + virtual void GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam); + + virtual void SetBindTargetParams(const PeerTargetId &targetId); + // Register the notification function when the auth_mgr event is complete. + virtual void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); + + // Public functions + static std::string ConvertSrcVersion(const std::string &version, const std::string &edition); + static int32_t DmGetUserId(int32_t displayId); + bool IsTransferReady(); + void SetTransferReady(bool version); + +protected: + bool isTransferReady_ = true; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_ADAPTER_V2_H diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h new file mode 100644 index 000000000..a2debab84 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -0,0 +1,332 @@ +/* + * Copyright (c) 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. + */ + +#ifndef OHOS_DM_AUTH_MESSAGE_PROCESSOR_V2_H +#define OHOS_DM_AUTH_MESSAGE_PROCESSOR_V2_H + +#include + +#include "access_control_profile.h" +#include "crypto_mgr.h" +#include "deviceprofile_connector.h" +#include "json_object.h" + +namespace OHOS { +namespace DistributedHardware { +struct DmAuthContext; +struct DmAccess; + +extern const char* TAG_LNN_PUBLICK_KEY; +extern const char* TAG_TRANSMIT_PUBLICK_KEY; +extern const char* TAG_LNN_CREDENTIAL_ID; +extern const char* TAG_TRANSMIT_CREDENTIAL_ID; +extern const char* TAG_AUTH_RESULT; +extern const char* TAG_AUTH_TYPE_LIST; +extern const char* TAG_CURRENT_AUTH_TYPE_IDX; + +// IS interface input parameter json format string key +extern const char* TAG_METHOD; +extern const char* TAG_PEER_USER_SPACE_ID; +extern const char* TAG_SUBJECT; +extern const char* TAG_CRED_TYPE; +extern const char* TAG_KEY_FORMAT; +extern const char* TAG_ALGORITHM_TYPE; +extern const char* TAG_PROOF_TYPE; +extern const char* TAG_KEY_VALUE; +extern const char* TAG_AUTHORIZED_SCOPE; +extern const char* TAG_AUTHRIZED_APP_LIST; +extern const char* TAG_CREDENTIAL_OWNER; +extern const char* TAG_SYNC; +extern const char* TAG_ACCESS; +extern const char* TAG_PROXY; +extern const char* TAG_ACL; +extern const char* TAG_ACCESSER; +extern const char* TAG_ACCESSEE; +extern const char* TAG_SERVICEINFO; +// The local SK information is synchronized to the remote end to construct acl-accesser/accessee. +extern const char* TAG_TRANSMIT_SK_ID; +extern const char* TAG_LNN_SK_ID; +extern const char* TAG_TRANSMIT_SK_TIMESTAMP; +extern const char* TAG_LNN_SK_TIMESTAMP; +extern const char* TAG_USER_ID; +extern const char* TAG_TOKEN_ID; +extern const char* TAG_ISSUER; + +extern const char* TAG_DEVICE_VERSION; +extern const char* TAG_DEVICE_NAME; +extern const char* TAG_DEVICE_ID_HASH; +extern const char* TAG_USER_ID_HASH; +extern const char* TAG_ACCOUNT_ID_HASH; +extern const char* TAG_TOKEN_ID_HASH; +extern const char* TAG_SESSION_NAME; +extern const char* TAG_ACL_CHECKSUM; +extern const char* TAG_COMPRESS_ORI_LEN; +extern const char* TAG_COMPRESS; +extern const char* TAG_REPLY; +extern const char* TAG_STATE; +extern const char* TAG_REASON; +extern const char* TAG_PEER_USER_ID; +extern const char* TAG_PEER_DISPLAY_ID; +extern const char* TAG_EXTRA_INFO; + +extern const char* TAG_IS_ONLINE; +extern const char* TAG_IS_AUTHED; +extern const char* TAG_CREDENTIAL_INFO; +extern const char* TAG_CERT_INFO; +extern const char* TAG_LANGUAGE; + +// Accesser table content is used for ACL synchronization. +extern const char* TAG_ACCESSER_DEVICE_ID; +extern const char* TAG_ACCESSER_USER_ID; +extern const char* TAG_ACCESSER_ACOUNT_ID; +extern const char* TAG_ACCESSER_TOKEN_ID; +extern const char* TAG_ACCESSER_SERVICE_NAME; +extern const char* TAG_ACCESSER_BUNDLE_NAME; +extern const char* TAG_ACCESSER_HAP_SIGNATURE; +extern const char* TAG_ACCESSER_BIND_LEVEL; +extern const char* TAG_ACCESSER_CREDENTIAL_ID; +extern const char* TAG_ACCESSER_STATUS; +extern const char* TAG_ACCESSER_SK_ID; +extern const char* TAG_ACCESSER_SK_TIMESTAMP; + +// Accessee table content is used for ACL synchronization. +extern const char* TAG_ACCESSEE_DEVICE_ID; +extern const char* TAG_ACCESSEE_USER_ID; +extern const char* TAG_ACCESSEE_ACOUNT_ID; +extern const char* TAG_ACCESSEE_TOKEN_ID; +extern const char* TAG_ACCESSEE_SERVICE_NAME; +extern const char* TAG_ACCESSEE_BUNDLE_NAME; +extern const char* TAG_ACCESSEE_HAP_SIGNATURE; +extern const char* TAG_ACCESSEE_BIND_LEVEL; +extern const char* TAG_ACCESSEE_CREDENTIAL_ID; +extern const char* TAG_ACCESSEE_STATUS; +extern const char* TAG_ACCESSEE_SK_ID; +extern const char* TAG_ACCESSEE_SK_TIMESTAMP; + +// Logical Session Tag +constexpr const char* DM_TAG_LOGICAL_SESSION_ID = "logicalSessionId"; + +// Message type +enum DmMessageType { + // Terminate/Exception Message + MSG_TYPE_UNKNOWN = 0, + MSG_TYPE_AUTH_TERMINATE = 1, + // Normal Message + MSG_TYPE_REQ_ACL_NEGOTIATE = 80, + MSG_TYPE_RESP_ACL_NEGOTIATE = 90, + MSG_TYPE_REQ_USER_CONFIRM = 100, + MSG_TYPE_RESP_USER_CONFIRM = 110, + MSG_TYPE_REQ_PIN_AUTH_START = 120, + MSG_TYPE_RESP_PIN_AUTH_START = 130, + MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE = 121, + MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE = 131, + MSG_TYPE_REQ_CREDENTIAL_EXCHANGE = 140, + MSG_TYPE_RESP_CREDENTIAL_EXCHANGE = 150, + MSG_TYPE_REQ_CREDENTIAL_AUTH_START = 160, + MSG_TYPE_RESP_CREDENTIAL_AUTH_START = 170, + MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE = 161, + MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE = 171, + MSG_TYPE_REQ_DATA_SYNC = 180, + MSG_TYPE_RESP_DATA_SYNC = 190, + MSG_TYPE_AUTH_REQ_FINISH = 200, + MSG_TYPE_AUTH_RESP_FINISH = 201, +}; + +struct DmAccessControlTable { + int32_t accessControlId; + int64_t accesserId; + int64_t accesseeId; + std::string deviceId; + std::string sessionKey; + int32_t bindType; + uint32_t authType; + uint32_t deviceType; + std::string deviceIdHash; + int32_t status; + int32_t validPeriod; + int32_t lastAuthTime; + uint32_t bindLevel; +}; + +// Structure used for synchronizing ACL access +// Attention: Modifying this structure requires updating the From/ToJson functions in dm_auth_message_processor.cpp. +struct DmAccessToSync { + std::string deviceName; + // 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; + int32_t userId; + std::string accountId; + uint64_t tokenId; + std::string bundleName; // Stores the PacketName + int32_t bindLevel; // Passed through for business purposes, no custom definition required + int32_t sessionKeyId; // User credential ID + int64_t skTimeStamp; // Used for aging, time is 2 days, user-level credential timestamp +}; + +// json and struct conversion functions +void ToJson(JsonItemObject &itemObject, const DmAccessControlTable &table); +void FromJson(const JsonItemObject &itemObject, DmAccessControlTable &table); +void ToJson(JsonItemObject &itemObject, const DmAccessToSync &table); +void FromJson(const JsonItemObject &itemObject, DmAccessToSync &table); + +using JsonTypeCheckFuncPtr = bool (JsonItemObject::*)() const; + +template +void SetValueFromJson(const JsonItemObject &itemObject, const std::string &key, + JsonTypeCheckFuncPtr funcPtr, T &value) +{ + if (itemObject.Contains(key) && (itemObject[key].*funcPtr)()) { + value = itemObject[key].Get(); + } +} + +class DmAuthMessageProcessor { +public: + using CreateMessageFuncPtr = + int32_t (DmAuthMessageProcessor::*)(std::shared_ptr, JsonObject &jsonObject); + using ParaseMessageFuncPtr = + int32_t (DmAuthMessageProcessor::*)(const JsonObject &, std::shared_ptr); + + DmAuthMessageProcessor(); + ~DmAuthMessageProcessor(); + // Parse the message, and save the parsed information to the context + int32_t ParseMessage(std::shared_ptr context, const std::string &message); + // Create a message, construct the corresponding message based on msgType + std::string CreateMessage(DmMessageType msgType, std::shared_ptr context); + + // Create and send a message + void CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context); + + // Save the session key + int32_t SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); + + // Save the permanent session key to the data profile + int32_t SaveSessionKeyToDP(int32_t &skId); + + // Save the current access control list + int32_t PutAccessControlList(std::shared_ptr context, + DmAccess &access, std::string trustDeviceId); + + // Calculate the checksum for the access control list + bool ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl, + std::vector &accesserStrList, std::vector &accesseeStrList); + + // Extract the access control list (ACL) for message parsing and bus usage. + // If no ACL is available, return an empty string. The returned string is in + // JSON format: {dmversion:x,accesser:[{accesserDeviceId:y,...},...], accessee:{...}} + int32_t GetAclListStr(std::shared_ptr &context, std::string &aclList); +private: + // Internal implementations for various message types + + // Used to encrypt the synchronization message + int32_t EncryptSyncMessage(std::shared_ptr &context, DmAccess &accessSide, std::string &encSyncMsg); + // Parse the authentication start message + int32_t ParseAuthStartMessage(const JsonObject &jsonObject, std::shared_ptr context); + + // Parse the 80 message + int32_t ParseNegotiateMessage(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 90 message + int32_t ParseMessageRespAclNegotiate(const JsonObject &json, std::shared_ptr context); + // Parse the 100 message + int32_t ParseMessageReqUserConfirm(const JsonObject &json, std::shared_ptr context); + // Parse the 110 message + int32_t ParseMessageRespUserConfirm(const JsonObject &json, std::shared_ptr context); + // Parse the 120 message + int32_t ParseMessageReqPinAuthStart(const JsonObject &json, std::shared_ptr context); + // Parse the 130 message + int32_t ParseMessageRespPinAuthStart(const JsonObject &json, std::shared_ptr context); + // Parse the 121 message + int32_t ParseMessageReqPinAuthNegotiate(const JsonObject &json, std::shared_ptr context); + // Parse the 131 message + int32_t ParseMessageRespPinAuthNegotiate(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 140 message + int32_t ParseMessageReqCredExchange(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 150 message + int32_t ParseMessageRspCredExchange(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 161, 170, and 171 messages + int32_t ParseMessageNegotiateTransmit(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 180 message + int32_t ParseMessageSyncReq(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 190 message + int32_t ParseMessageSyncResp(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 200 message + int32_t ParseMessageSinkFinish(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 201 message + int32_t ParseMessageSrcFinish(const JsonObject &jsonObject, std::shared_ptr context); + + // Create the 80 message + int32_t CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); + // Create the 90 message + int32_t CreateRespNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); + // Create the 100 message + int32_t CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json); + // Create the 110 message + int32_t CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json); + // Create the 120 message + int32_t CreateMessageReqPinAuthStart(std::shared_ptr context, JsonObject &json); + // Create the 130 message + int32_t CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json); + // Create the 121 message + int32_t CreateMessageReqPinAuthNegotiate(std::shared_ptr context, JsonObject &json); + // Create the 131 message + int32_t CreateMessageRespPinAuthNegotiate(std::shared_ptr context, JsonObject &json); + // Create the 140 message + int32_t CreateMessageReqCredExchange(std::shared_ptr context, JsonObject &jsonObject); + // Create the 150 message + int32_t CreateMessageRspCredExchange(std::shared_ptr context, JsonObject &jsonObject); + // Create the 160 message + int32_t CreateMessageReqCredAuthStart(std::shared_ptr context, JsonObject &jsonObject); + // Construct the 161, 170, and 171 credential authentication messages + int32_t CreateCredentialNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); + // Construct the 180 and 190 sync messages + int32_t CreateSyncMessage(std::shared_ptr context, JsonObject &jsonObject); + // Create the 190 message + int32_t CreateMessageSyncResp(std::shared_ptr context, JsonObject &jsonObject); + // Create the 200 message + int32_t CreateMessageFinish(std::shared_ptr context, JsonObject &jsonObject); + + // Compress the sync message + std::string CompressSyncMsg(std::string &inputStr); + // Decompress the sync message + std::string DecompressSyncMsg(std::string& compressed, uint32_t oriLen); + // Serialize the ACL + int32_t ACLToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string aclStr); + // Decrypt the 180 and 190 messages + int32_t DecryptSyncMessage(std::shared_ptr &context, + DmAccess &access, std::string &enSyncMsg); + // Parse the sync message + int32_t ParseSyncMessage(std::shared_ptr &context, + DmAccess &access, JsonObject &jsonObject); + + // Convert the accesser_table record in DP to a string + std::string AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl); + // Convert the accessee_table record in DP to a string + std::string AccesseeToStr(DistributedDeviceProfile::AccessControlProfile acl); + std::string Base64Encode(std::string &inputStr); + std::string Base64Decode(std::string &inputStr); + void SetAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::AccessControlProfile &profile); + void SetTransmitAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); + void SetLnnAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); + std::shared_ptr cryptoMgr_ = nullptr; + std::unordered_map createMessageFuncMap_; + std::unordered_map paraseMessageFuncMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MESSAGE_PROCESSOR_V2_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h new file mode 100644 index 000000000..f5af9a12d --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -0,0 +1,445 @@ +/* + * Copyright (c) 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. + */ + +#ifndef OHOS_DM_AUTH_STATE_V2_H +#define OHOS_DM_AUTH_STATE_V2_H + +#include + +#include "access_control_profile.h" +#include "dm_auth_context.h" + +namespace OHOS { +namespace DistributedHardware { +const char* const FILED_CRED_OWNER = "credOwner"; +const char* const FILED_DEVICE_ID = "deviceId"; +const char* const FILED_USER_ID = "userId"; +const char* const FILED_DEVICE_ID_HASH = "deviceIdHash"; +const char* const FILED_PEER_USER_SPACE_ID = "peerUserSpaceId"; +const char* const FILED_CRED_ID = "credId"; +const char* const FILED_CRED_TYPE = "credType"; +const char* const FILED_AUTHORIZED_SCOPE = "authorizedScope"; +const char* const FILED_AUTHORIZED_APP_LIST = "authorizedAppList"; +const char* const FILED_SUBJECT = "subject"; + +// State Types +enum class DmAuthStateType { + AUTH_IDLE_STATE = 0, // When the device is initialized + // source end state + AUTH_SRC_START_STATE = 1, // User triggers BindTarget + AUTH_SRC_NEGOTIATE_STATE = 2, // Receive softbus callback OnSessionOpened, send 80 message + AUTH_SRC_CONFIRM_STATE = 3, // Receive 90 authorization result message, send 100 message + AUTH_SRC_PIN_NEGOTIATE_START_STATE = 4, // Start negotiating PIN code, receive 110 authorization message + // or rollback or 90 jump + AUTH_SRC_PIN_INPUT_STATE = 5, // Enter PIN + AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE = 6, // Ultrasonic PIN negotiation + AUTH_SRC_PIN_AUTH_START_STATE = 7, // Start authentication and send 120 message. + AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE = 8, // Receive 130 authentication PIN result message, send 121 message + AUTH_SRC_PIN_AUTH_DONE_STATE = 9, // Receive 131 authentication PIN result message, call processData + AUTH_SRC_CREDENTIAL_EXCHANGE_STATE = 10, // Trigger the Onfinish callback event and send a 140 message + AUTH_SRC_CREDENTIAL_AUTH_START_STATE = 11, // Received 150 encrypted messages, sent 160 messages + AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE = 12, // 收到170凭据认证报文,发送161报文 + AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE = 13, // Received 170 credential authentication message, sent 161 message + AUTH_SRC_DATA_SYNC_STATE = 14, // Received 190 message, sent 200 message + AUTH_SRC_FINISH_STATE = 15, // Received 201 message + + // sink end state + AUTH_SINK_START_STATE = 50, // Bus trigger OnSessionOpened + AUTH_SINK_NEGOTIATE_STATE = 51, // Received 80 trusted relationship negotiation message, send 90 message + AUTH_SINK_CONFIRM_STATE = 52, // Received 100 user authorization messages, sent 110 messages + AUTH_SINK_PIN_NEGOTIATE_START_STATE = 53, // Start negotiating PIN code, active migration or error rollback + AUTH_SINK_PIN_DISPLAY_STATE = 54, // Generate and display PIN + AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE = 55, // Negotiate ultrasonic PIN status passive trigger or + // other status active migration to enter ultrasonic + AUTH_SINK_PIN_AUTH_START_STATE = 56, // Receive 120 authentication PIN message, send 130 message + AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE = 57, // Received 121 authentication PIN message, send 131 message + AUTH_SINK_PIN_AUTH_DONE_STATE = 58, // Trigger the Onfinish callback event + AUTH_SINK_CREDENTIAL_EXCHANGE_STATE = 59, // Received 140 encrypted messages, sent 150 messages + AUTH_SINK_CREDENTIAL_AUTH_START_STATE = 60, // Receive 160 authentication message, send 170 message + AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE = 61, // Received 161 credential negotiation message, + // reply with 171 message + AUTH_SINK_DATA_SYNC_STATE = 62, // Received 180 synchronization message, send 190 message + AUTH_SINK_FINISH_STATE = 63, // Received 200 end message, send 201 message +}; + +// Credential Addition Method +enum DmAuthCredentialAddMethod : uint8_t { + DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE = 1, // Generate + DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, // Import +}; + +// Credential Subject +enum DmAuthCredentialSubject : uint8_t { + DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY = 1, // Main Control + DM_AUTH_CREDENTIAL_SUBJECT_SUPPLEMENT, // Accessories +}; + +// Credentials and account association +enum DmAuthCredentialAccountRelation : uint8_t { + DM_AUTH_CREDENTIAL_INVALID = 0, // Invalid + DM_AUTH_CREDENTIAL_ACCOUNT_RELATED = 1, // Account related + DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED = 2, // Account independent + DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS = 3, // Share +}; + +// Key Type +enum DmAuthKeyFormat : uint8_t { + DM_AUTH_KEY_FORMAT_SYMM_IMPORT = 1, // Symmetric key (supported only for import) + DM_AUTH_KEY_FORMAT_ASYMM_IMPORT, // Asymmetric key public key (supported only for import) + DM_AUTH_KEY_FORMAT_ASYMM_GENERATE, // Asymmetric key (supported only for generation) + DM_AUTH_KEY_FORMAT_X509, // X509 certificate +}; + +// Algorithm type +enum DmAuthAlgorithmType : uint8_t { + DM_AUTH_ALG_TYPE_AES256 = 1, // AES256 + DM_AUTH_ALG_TYPE_AES128, // AES128 + DM_AUTH_ALG_TYPE_P256, // P256 + DM_AUTH_ALG_TYPE_ED25519 // ED25519 +}; + +// Credential proof type +enum DmAuthCredentialProofType : uint8_t { + DM_AUTH_CREDENTIAL_PROOF_PSK = 1, // PSK + DM_AUTH_CREDENTIAL_PROOF_PKI, // PKI +}; + +enum DmCredType : uint8_t { + ACCOUNT_RELATED = 1, + ACCOUNT_UNRELATED, + ACCOUNT_ACROSS +}; + +enum DmAuthorizedScope : uint8_t { + SCOPE_DEVICE = 1, + SCOPE_USER, + SCOPE_APP, +}; + +enum DM_SUBJECT : uint8_t { + SUBJECT_PRIMARY = 1, + SUBJECT_SECONDARY, +}; + +class DmAuthState { +public: + virtual ~DmAuthState() {}; + virtual DmAuthStateType GetStateType() = 0; + virtual int32_t Action(std::shared_ptr context) = 0; + void SyncAclList(std::shared_ptr context, int32_t userId, + std::string credId, int32_t sessionKeyId, int32_t aclId); + void SourceFinish(std::shared_ptr context); + void SinkFinish(std::shared_ptr context); + std::string GenerateBindResultContent(DmAccess &access); + static bool IsScreenLocked(); + static int32_t GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut); + static void HandleAuthenticateTimeout(std::shared_ptr context, std::string name); + static bool IsImportAuthCodeCompatibility(DmAuthType authType); + + // Compare the plaintext and ciphertext quadruples and binding levels. + bool IsQuadrupleAndBindLevelSame(std::shared_ptr context); + // Query the ACL list + std::vector GetAclList(std::shared_ptr context); + void SetAclExtraInfo(std::shared_ptr context); + void SetAclInfo(std::shared_ptr context); + int32_t GetAclBindType(std::shared_ptr context, std::string credId); +protected: + bool NeedReqUserConfirm(std::shared_ptr context); + bool NeedAgreeCredential(std::shared_ptr context); + bool NeedAgreeAcl(std::shared_ptr context); +}; + +class AuthSrcConfirmState : public DmAuthState { +public: + virtual ~AuthSrcConfirmState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + void NegotiateCredential(std::shared_ptr context, JsonObject &credTypeNegoRsult); + void NegotiateAcl(std::shared_ptr context, JsonObject &aclNegoRsult); + void GetSrcCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetIdenticalCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetShareCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetP2PCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo); + void GetSrcAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo); + bool IdenticalAccountAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool ShareAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool Point2PointAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool LnnAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool CheckCredIdInAcl(const DistributedDeviceProfile::AccessControlProfile &profile, + JsonObject &credInfo, uint32_t bindType); + void GetSrcCredType(std::shared_ptr context, JsonObject &credInfo, JsonObject &credTypeJson); + bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); +}; + +class AuthSinkStatePinAuthComm { +public: + static bool IsPinCodeValid(int32_t numpin); + static bool IsPinCodeValid(const std::string& strpin); + static bool IsAuthCodeReady(std::shared_ptr context); + static void GeneratePincode(std::shared_ptr context); + static int32_t ShowAuthInfoDialog(std::shared_ptr context); +private: + static void HandleSessionHeartbeat(std::shared_ptr context, std::string name); +}; + +class AuthSinkConfirmState : public DmAuthState { +public: + virtual ~AuthSinkConfirmState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + void NegotiateCredential(std::shared_ptr context, JsonObject &credTypeNegoRsult); + void NegotiateAcl(std::shared_ptr context, JsonObject &aclNegoRsult); + int32_t ShowConfigDialog(std::shared_ptr context); + void ReadServiceInfo(std::shared_ptr context); + void MatchFallBackCandidateList(std::shared_ptr context, DmAuthType authType); + int32_t ProcessBindAuthorize(std::shared_ptr context); + int32_t ProcessNoBindAuthorize(std::shared_ptr context); + std::string GetCredIdByCredType(std::shared_ptr context, int32_t credType); +}; + +class AuthSrcPinNegotiateStartState : public DmAuthState { +public: + virtual ~AuthSrcPinNegotiateStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t NegotiatePinAuth(std::shared_ptr context, bool firstTime); + int32_t ProcessCredAuth(std::shared_ptr context); + int32_t ProcessPinBind(std::shared_ptr context); + std::string GetCredIdByCredType(std::shared_ptr context, int32_t credType); +}; + +class AuthSrcPinInputState : public DmAuthState { +public: + virtual ~AuthSrcPinInputState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t ShowStartAuthDialog(std::shared_ptr context); +}; + +class AuthSinkPinNegotiateStartState : public DmAuthState { +public: + virtual ~AuthSinkPinNegotiateStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinDisplayState : public DmAuthState { +public: + virtual ~AuthSinkPinDisplayState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinNegotiateUltrasonicPinState : public DmAuthState { +public: + virtual ~AuthSrcPinNegotiateUltrasonicPinState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinNegotiateUltrasonicPinState : public DmAuthState { +public: + virtual ~AuthSinkPinNegotiateUltrasonicPinState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinAuthStartState : public DmAuthState { +public: + virtual ~AuthSrcPinAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t ShowStartAuthDialog(std::shared_ptr context); // Display PIN input box to user +}; + +class AuthSinkPinAuthStartState : public DmAuthState { +public: + virtual ~AuthSinkPinAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinAuthMsgNegotiateState : public DmAuthState { +public: + virtual ~AuthSrcPinAuthMsgNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinAuthMsgNegotiateState : public DmAuthState { +public: + virtual ~AuthSinkPinAuthMsgNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinAuthDoneState : public DmAuthState { +public: + virtual ~AuthSinkPinAuthDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinAuthDoneState : public DmAuthState { +public: + virtual ~AuthSrcPinAuthDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcStartState : public DmAuthState { +public: + virtual ~AuthSrcStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcNegotiateStateMachine : public DmAuthState { +public: + virtual ~AuthSrcNegotiateStateMachine() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +// Middle class encapsulates public interfaces related to business. +class AuthCredentialAgreeState : public DmAuthState { +public: + virtual ~AuthCredentialAgreeState() {}; +protected: + std::string CreateAuthParamsString(DmAuthScope authorizedScope, DmAuthCredentialAddMethod method, + const std::shared_ptr &authContext); + int32_t GenerateCredIdAndPublicKey(DmAuthScope authorizedScope, std::shared_ptr &authContext); + int32_t AgreeCredential(DmAuthScope authorizedScope, std::shared_ptr &authContext); +}; + +class AuthSrcCredentialExchangeState : public AuthCredentialAgreeState { +public: + virtual ~AuthSrcCredentialExchangeState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkCredentialExchangeState : public AuthCredentialAgreeState { +public: + virtual ~AuthSinkCredentialExchangeState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcCredentialAuthStartState : public AuthCredentialAgreeState { +public: + virtual ~AuthSrcCredentialAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcCredentialAuthNegotiateState : public DmAuthState { +public: + virtual ~AuthSrcCredentialAuthNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcCredentialAuthDoneState : public DmAuthState { +public: + virtual ~AuthSrcCredentialAuthDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkCredentialAuthStartState : public DmAuthState { +public: + virtual ~AuthSinkCredentialAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkCredentialAuthNegotiateState : public DmAuthState { +public: + virtual ~AuthSinkCredentialAuthNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkNegotiateStateMachine : public DmAuthState { +public: + virtual ~AuthSinkNegotiateStateMachine() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; + +private: + int32_t RespQueryAcceseeIds(std::shared_ptr context); + int32_t ProcRespNegotiate5_1_0(std::shared_ptr context); + void GetSinkCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetIdenticalCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetShareCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + void GetP2PCredentialInfo(std::shared_ptr context, JsonObject &credInfo); + uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo); + void GetSinkAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo); + bool IdenticalAccountAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool ShareAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool Point2PointAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool LnnAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool CheckCredIdInAcl(const DistributedDeviceProfile::AccessControlProfile &profile, + JsonObject &credInfo, uint32_t bindType); + void GetSinkCredType(std::shared_ptr context, JsonObject &credInfo, JsonObject &credTypeJson); + bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); + +}; + +class AuthSinkDataSyncState : public DmAuthState { +public: + virtual ~AuthSinkDataSyncState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcDataSyncState : public DmAuthState { +public: + virtual ~AuthSrcDataSyncState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkFinishState : public DmAuthState { +public: + virtual ~AuthSinkFinishState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcFinishState : public DmAuthState { +public: + virtual ~AuthSrcFinishState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_STATE_V2_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h new file mode 100644 index 000000000..00a4c80e2 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -0,0 +1,118 @@ +/* + * Copyright (c) 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. + */ + +#ifndef OHOS_DM_AUTH_STATE_MACHINE_V2_H +#define OHOS_DM_AUTH_STATE_MACHINE_V2_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dm_auth_state.h" + +namespace OHOS { +namespace DistributedHardware { + +// Define the state transition table type +using StateTransitionTable = std::map>; + +enum DmEventType { + ON_TRANSMIT = 0, + ON_SESSION_KEY_RETURNED, + ON_REQUEST, + ON_FINISH, + ON_ERROR, + + ON_TIMEOUT, + ON_USER_OPERATION, + ON_FAIL, + ON_SCREEN_LOCKED, + ON_SESSION_OPENED, +}; + +class DmAuthStateMachine { +public: + DmAuthStateMachine(std::shared_ptr context); + ~DmAuthStateMachine(); + + // Notify state transition, execute the corresponding action for the state, and handle exceptions + // only allowed to be called within OnDataReceived + int32_t TransitionTo(std::shared_ptr state); + + // Wait for the expected event within the action, block until the expected event is completed or + // an exception occurs, returning the actual event that occurred (only allowed to be called within actions) + DmEventType WaitExpectEvent(DmEventType eventType); + + // Notify the completion of an event, passing the event enumeration + // (only allowed to be called when the event is triggered). If it's an exception event, + // record it in the context's reason or reply. + void NotifyEventFinish(DmEventType eventType); + + DmAuthStateType GetCurState(); + + // Stop the thread + void Stop(); + +private: + // Loop to wait for state transitions and execute actions + void Run(std::shared_ptr context); + void InsertSrcTransTable(); + void InsertSinkTransTable(); + + // Fetch the current state and execute it + std::optional> FetchAndSetCurState(); + + void SetCurState(DmAuthStateType state); + + bool CheckStateTransitValid(DmAuthStateType nextState); + + DmAuthStateType curState_; + + // State transition table for normal state transitions (all state transitions to the Finish state are valid) + StateTransitionTable stateTransitionTable_; + + std::queue eventQueue_; + + // Set of exception events + std::set exceptionEvent_; + + // Atomic flag to control the state machine's running state + std::atomic running_; + + // Queue for storing states + std::queue> statesQueue_; + + // Synchronization primitives + std::mutex stateMutex_; + std::condition_variable stateCv_; + std::mutex eventMutex_; + std::condition_variable eventCv_; + + // Direction of authentication + DmAuthDirection direction_; + int32_t reason{DM_OK}; + + // Thread for state machine execution + std::thread thread_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_STATE_MACHINE_V2_H diff --git a/services/implementation/include/authentication_v2/dm_negotiate_process.h b/services/implementation/include/authentication_v2/dm_negotiate_process.h new file mode 100644 index 000000000..4a58433a1 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_negotiate_process.h @@ -0,0 +1,191 @@ +/* + * Copyright (c) 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. + */ +#ifndef OHOS_DM_NEGOTIATE_PROCESS_V2_H +#define OHOS_DM_NEGOTIATE_PROCESS_V2_H +#include +#include +#include + +#include "dm_auth_context.h" +#include "dm_single_instance.h" +namespace OHOS { +namespace DistributedHardware { +enum CredType : uint8_t { + DM_NO_CRED = 0, + DM_IDENTICAL_CREDTYPE = 1, + DM_SHARE_CREDTYPE = 2, + DM_P2P_CREDTYPE = 3, +}; + +enum AclType : uint8_t { + DM_NO_ACL = 0, + DM_IDENTICAL_ACL = 1, + DM_SHARE_ACL = 2, + DM_P2P_ACL = 3, +}; + +enum AuthType : uint8_t { + DM_INVALIED_AUTHTYPE = 0, + DM_INPUT_PINCODE = 1, + DM_IMPORT_AUTHTYPE = 2, +}; + +class NegotiateSpec { +public: + CredType credType; + AclType aclType; + AuthType authType; + + NegotiateSpec(CredType credTypeTemp, AclType aclTypeTemp, AuthType authTypeTemp) + : credType(credTypeTemp), aclType(aclTypeTemp), authType(authTypeTemp) {} + + // 重载<运算符用于map排序 + bool operator<(const NegotiateSpec& other) const { + if (credType != other.credType) return credType < other.credType; + if (aclType != other.aclType) return aclType < other.aclType; + return authType < other.authType; + } +}; + +class NegotiateHandler { +public: + virtual int32_t NegotiateHandle(std::shared_ptr context) = 0; + virtual ~NegotiateHandler() {}; +}; + +class NoCredNoAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~NoCredNoAclInputAuthType() {}; +}; + +class NoCredNoAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~NoCredNoAclImportAuthType() {}; +}; + +class IdentCredNoAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~IdentCredNoAclInputAuthType() {}; +}; + +class IdentCredNoAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~IdentCredNoAclImportAuthType() {}; +}; + +class IdentCredIdentAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~IdentCredIdentAclInputAuthType() {}; +}; + +class IdentCredIdentAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~IdentCredIdentAclImportAuthType() {}; +}; + +class IdentCredP2pAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~IdentCredP2pAclInputAuthType() {}; +}; + +class IdentCredP2pAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~IdentCredP2pAclImportAuthType() {}; +}; + +class ShareCredNoAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~ShareCredNoAclInputAuthType() {}; +}; + +class ShareCredNoAclImputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~ShareCredNoAclImputAuthType() {}; +}; + +class ShareCredShareAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~ShareCredShareAclInputAuthType() {}; +}; + +class ShareCredShareAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~ShareCredShareAclImportAuthType() {}; +}; + +class ShareCredP2pAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~ShareCredP2pAclInputAuthType() {}; +}; + +class ShareCredP2pAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~ShareCredP2pAclImportAuthType() {}; +}; + +class P2pCredNoAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~P2pCredNoAclInputAuthType() {}; +}; + +class P2pCredNoAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~P2pCredNoAclImportAuthType() {}; +}; + +class P2pCredP2pAclInputAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~P2pCredP2pAclInputAuthType() {}; +}; + +class P2pCredP2pAclImportAuthType : public NegotiateHandler { +public: + int32_t NegotiateHandle(std::shared_ptr context) override; + virtual ~P2pCredP2pAclImportAuthType() {}; +}; + +class NegotiateProcess { +DM_DECLARE_SINGLE_INSTANCE_BASE(NegotiateProcess); +public: + NegotiateProcess(); + ~NegotiateProcess(); + int32_t HandleNegotiateResult(std::shared_ptr context); +private: + CredType ConvertCredType(const std::string &credType); + AclType ConvertAclType(const std::string &aclType); + AuthType ConvertAuthType(const DmAuthType &authType); +private: + std::map> handlers_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_STATE_V2_H \ No newline at end of file diff --git a/services/implementation/include/cryptomgr/crypto_mgr.h b/services/implementation/include/cryptomgr/crypto_mgr.h index 86a759081..e31e27c15 100644 --- a/services/implementation/include/cryptomgr/crypto_mgr.h +++ b/services/implementation/include/cryptomgr/crypto_mgr.h @@ -45,6 +45,7 @@ public: int32_t SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); int32_t ProcessSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); void ClearSessionKey(); + std::vector GetSessionKey(); private: int32_t DoEncryptData(AesGcmCipherKey *cipherKey, const unsigned char *input, uint32_t inLen, diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index 460a4094d..5684ef0c9 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -16,7 +16,9 @@ #ifndef OHOS_HICHAIN_AUTH_CONNECTOR_H #define OHOS_HICHAIN_AUTH_CONNECTOR_H +#include #include + #include "device_auth.h" #include "device_auth_defines.h" #include "hichain_connector_callback.h" @@ -53,16 +55,33 @@ public: int32_t ProcessAuthData(int64_t requestId, std::string authData, int32_t osAccountId); int32_t GenerateCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey); bool QueryCredential(std::string &localUdid, int32_t osAccountId); + int32_t QueryCredentialInfo(int32_t userId, const JsonObject &queryParams, JsonObject &resultJson); + int32_t QueryCredInfoByCredId(int32_t userId, std::string credId, JsonObject &resultJson); int32_t ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey); int32_t DeleteCredential(const std::string &deviceId, int32_t userId); int32_t RegisterHiChainAuthCallback(std::shared_ptr callback); + int32_t RegisterHiChainAuthCallbackById(int64_t id, std::shared_ptr callback); int32_t GetCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey); + + int32_t ProcessCredData(int64_t authReqId, const std::string &data); + int32_t AddCredential(int32_t osAccountId, const std::string &authParams, std::string &creId); + int32_t ExportCredential(int32_t osAccountId, const std::string &credId, std::string &publicKey); + int32_t AgreeCredential(int32_t osAccountId, const std::string selfCredId, const std::string &authParams, + std::string &credId); + int32_t DeleteCredential(int32_t osAccountId, const std::string &creId); + // Credential authentication pinCode Pin code (required for point-to-point temporary credentials) + int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, + const std::string &pinCode); + int32_t AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode); + private: void FreeJsonString(char *jsonStr); + static std::shared_ptr GetDeviceAuthCallback(int64_t id); private: DeviceAuthCallback deviceAuthCallback_; static std::shared_ptr dmDeviceAuthCallback_; + static std::map> dmDeviceAuthCallbackMap_; static std::mutex dmDeviceAuthCallbackMutex_; }; } // namespace DistributedHardware diff --git a/services/implementation/include/dependency/hichain/hichain_connector.h b/services/implementation/include/dependency/hichain/hichain_connector.h index c6e518cad..c6210ddd8 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_connector.h @@ -155,7 +155,7 @@ public: * @tc.type: FUNC */ bool GetGroupInfo(const int32_t userId, const std::string &queryParams, std::vector &groupList); - + bool GetGroupInfoExt(const int32_t userId, const std::string &queryParams, std::vector &groupList); bool GetGroupInfoCommon(const int32_t userId, const std::string &queryParams, const char* pkgName, diff --git a/services/implementation/include/dependency/hichain/hichain_connector_callback.h b/services/implementation/include/dependency/hichain/hichain_connector_callback.h index 1e8e73f43..56dd42bbc 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector_callback.h +++ b/services/implementation/include/dependency/hichain/hichain_connector_callback.h @@ -37,8 +37,7 @@ public: virtual void AuthDeviceFinish(int64_t requestId) = 0; virtual void AuthDeviceError(int64_t requestId, int32_t errorCode) = 0; virtual void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) = 0; - virtual int32_t GetPinCode(int32_t &code) = 0; - virtual void GetRemoteDeviceId(std::string &deviceId) = 0; + virtual char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index 718d7ddeb..a9249f471 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -49,7 +49,7 @@ public: * @tc.desc: Get Connect Addr of the SoftbusConnector * @tc.type: FUNC */ - static ConnectionAddr *GetConnectAddr(const std::string &deviceId, std::string &connectAddr); + static std::shared_ptr GetConnectAddr(const std::string &deviceId, std::string &connectAddr); /** * @tc.name: SoftbusConnector::GetUdidByNetworkId @@ -86,6 +86,11 @@ public: */ static void JoinLnnByHml(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId); + static void JoinLnn(const std::string &deviceId, const std::string &remoteUdidHash); + + static void JoinLNNBySkId(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId, + std::string udid, std::string udidHash); + /** * @tc.name: SoftbusConnector::RegisterConnectorCallback * @tc.desc: RegisterConnectorCallback of the Softbus Connector @@ -120,6 +125,7 @@ public: void HandleDeviceOffline(std::string deviceId); void SetProcessInfo(ProcessInfo processInfo); bool CheckIsOnline(const std::string &targetDeviceId); + bool CheckIsOnline(const std::string &targetDeviceIdHash, bool isHash); void SetProcessInfoVec(std::vector processInfoVec); std::vector GetProcessInfo(); void ClearProcessInfo(); @@ -131,6 +137,7 @@ private: static void ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceBasicInfo &dmDeviceBasicInfo); static ConnectionAddr *GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type); static void ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeBasicInfo, DmDeviceInfo &dmDeviceInfo); + static std::shared_ptr GetDeviceInfoFromMap(const std::string &deviceId); private: static std::string remoteUdidHash_; diff --git a/services/implementation/include/dependency/softbus/softbus_session.h b/services/implementation/include/dependency/softbus/softbus_session.h index 289a9cd60..b3dfc2840 100644 --- a/services/implementation/include/dependency/softbus/softbus_session.h +++ b/services/implementation/include/dependency/softbus/softbus_session.h @@ -33,7 +33,6 @@ class SoftbusSession { public: static int OnSessionOpened(int sessionId, int result); static void OnSessionClosed(int sessionId); - static void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen); public: SoftbusSession(); @@ -91,7 +90,6 @@ public: private: static std::shared_ptr sessionCallback_; - ISocketListener iSocketListener_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 137b8cf2d..e5004db1d 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -16,24 +16,48 @@ #ifndef OHOS_DM_SERVICE_IMPL_H #define OHOS_DM_SERVICE_IMPL_H +#include +#include +#include +#include #include #include #include "access_control_profile.h" +#include "auth_manager.h" #include "dm_ability_manager.h" #include "dm_auth_manager.h" +#include "dm_auth_manager_base.h" #include "dm_common_event_manager.h" #include "dm_credential_manager.h" #include "dm_device_info.h" #include "dm_device_state_manager.h" +#include "dm_single_instance.h" #include "dp_inited_callback.h" #include "idevice_manager_service_impl.h" -#include "dm_single_instance.h" -#include "softbus_connector.h" #include "mine_hichain_connector.h" +#include "softbus_connector.h" namespace OHOS { namespace DistributedHardware { + +class Session { +public: + Session(int sessionId, std::string deviceId); + int sessionId_; + std::string deviceId_; + std::string version_{""}; + std::atomic flag_{false}; // Only one session is allowed + std::set logicalSessionSet_; // Logical Session Set + std::atomic logicalSessionCnt_{0}; +}; + +struct Config { + std::string pkgName; + std::string authCode; + int32_t authenticationType{0}; +}; + class DeviceManagerServiceImpl : public IDeviceManagerServiceImpl { public: DeviceManagerServiceImpl(); @@ -137,6 +161,15 @@ public: void DeleteAlwaysAllowTimeOut(); void CheckDeleteCredential(const std::string &remoteUdid); int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId); + int32_t DeleteAcl(const std::string &sessionName, const std::string &localUdid, const std::string &remoteUdid, + int32_t bindLevel, const std::string &extra); + int32_t DeleteAclV2(const std::string &sessionName, const std::string &localUdid, const std::string &remoteUdid, + int32_t bindLevel, const std::string &extra); + static void NotifyCleanEvent(int64_t logicalSessionId); + void HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId); + int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); + private: int32_t PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); @@ -153,20 +186,70 @@ private: void HandleUserRemoved(int32_t preUserId); void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); + int32_t InitAndRegisterAuthMgr(bool isSrcSide, uint64_t tokenId, std::shared_ptr session, + int64_t logicalSessionId); + std::shared_ptr GetAuthMgr(); + std::shared_ptr GetAuthMgrByTokenId(uint64_t tokenId); + std::shared_ptr GetCurSession(int sessionId); + std::shared_ptr GetOrCreateSession(const std::string& deviceId, + const std::map &bindParam); + int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, + const std::map &bindParam); + std::shared_ptr GetConfigByTokenId(); + int OpenAuthSession(const std::string& deviceId, const std::map &bindParam); + + std::shared_ptr GetAuthMgrByMessage(int32_t msgType, int64_t logicalSessionId, + const JsonObject &jsonObject, std::shared_ptr curSession); + int32_t TransferOldAuthMgr(int32_t msgType, const JsonObject &jsonObject, + std::shared_ptr curSession); + int32_t TransferSrcOldAuthMgr(std::shared_ptr curSession); + int32_t TransferSinkOldAuthMgr(const JsonObject &jsonObject, std::shared_ptr curSession); + int32_t GetDeviceInfo(const PeerTargetId &targetId, std::string &addrType, std::string &deviceId, + std::shared_ptr deviceInfo, int32_t &index); + bool IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid, + int32_t tokenId, int32_t userId); + void ImportConfig(std::shared_ptr authMgr, uint64_t tokenId); + + // Resource cleanup thread + void CleanWorker(); + // Stop the thread + void Stop(); + int64_t FetchCleanEvent(); + void CleanAuthMgrByLogicalSessionId(int64_t logicalSessionId); + void CleanSessionMap(int sessionId, std::shared_ptr session); + void CleanSessionMapByLogicalSessionId(int64_t logicalSessionId); private: - std::shared_ptr authMgr_; + std::shared_ptr authMgr_; // Old protocol only + std::map> authMgrMap_; // New protocol sharing + std::shared_ptr hiChainConnector_; + std::shared_ptr hiChainAuthConnector_; std::shared_ptr deviceStateMgr_; std::shared_ptr softbusConnector_; std::shared_ptr abilityMgr_; - std::shared_ptr hiChainConnector_; std::shared_ptr mineHiChainConnector_; std::shared_ptr credentialMgr_; std::shared_ptr commonEventManager_; - std::shared_ptr hiChainAuthConnector_; std::shared_ptr listener_; std::atomic isCredentialType_ = false; sptr dpInitedCallback_ = nullptr; + + // The session ID corresponding to the device ID, used only on the src side + std::map deviceId2SessionIdMap_; + std::map> sessionsMap_; // sessionId corresponds to the session object + std::map deviceIdMutexMap_; // Lock corresponding to the device ID + std::mutex mapMutex_; // sessionsMap_的锁 + std::map sessionEnableCvMap_; // Condition variable corresponding to the session + std::map sessionEnableMutexMap_; // Lock corresponding to the session + std::map logicalSessionId2TokenIdMap_; // The relationship between multiple sessions and tokenId + std::map logicalSessionId2SessionIdMap_; // The relationship multiple sessions and physical sessionId + std::map> configsMap_; // Import when authMgr is not initialized + + std::thread thread_; + std::atomic running_; + static std::condition_variable cleanEventCv_; + static std::mutex cleanEventMutex_; + static std::queue cleanEventQueue_; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 2ad955b5e..a0778fe30 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -56,7 +56,7 @@ public: int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel, const std::string &extra); - + int32_t SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms); void HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo); @@ -159,6 +159,8 @@ public: void DeleteAlwaysAllowTimeOut(); void CheckDeleteCredential(const std::string &remoteUdid); int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId); + void HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/src/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index 11b35a762..d076d4b28 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -49,6 +49,7 @@ std::string DmDialogManager::customDescriptionStr_ = ""; std::string DmDialogManager::targetDeviceName_ = ""; std::string DmDialogManager::pinCode_ = ""; std::string DmDialogManager::hostPkgLabel_ = ""; +uint64_t DmDialogManager::tokenId_ = 0; int32_t DmDialogManager::deviceType_ = -1; DmDialogManager DmDialogManager::dialogMgr_; sptr DmDialogManager::dialogConnectionCallback_( @@ -78,24 +79,28 @@ void DmDialogManager::ShowConfirmDialog(const std::string param) std::string appOperationStr = ""; std::string customDescriptionStr = ""; std::string hostPkgLabel = ""; + uint64_t tokenId = 0; int32_t deviceType = -1; JsonObject jsonObject(param); if (!jsonObject.IsDiscarded()) { - if (IsString(jsonObject, TAG_REQUESTER)) { + if (jsonObject[TAG_REQUESTER].IsString()) { deviceName = jsonObject[TAG_REQUESTER].Get(); } - if (IsString(jsonObject, TAG_APP_OPERATION)) { + if (jsonObject[TAG_APP_OPERATION].IsString()) { appOperationStr = jsonObject[TAG_APP_OPERATION].Get(); } - if (IsString(jsonObject, TAG_CUSTOM_DESCRIPTION)) { + if (jsonObject[TAG_CUSTOM_DESCRIPTION].IsString()) { customDescriptionStr = jsonObject[TAG_CUSTOM_DESCRIPTION].Get(); } - if (IsInt32(jsonObject, TAG_LOCAL_DEVICE_TYPE)) { + if (jsonObject[TAG_LOCAL_DEVICE_TYPE].IsNumberInteger()) { deviceType = jsonObject[TAG_LOCAL_DEVICE_TYPE].Get(); } - if (IsString(jsonObject, TAG_HOST_PKGLABEL)) { + if (jsonObject[TAG_HOST_PKGLABEL].IsString()) { hostPkgLabel = jsonObject[TAG_HOST_PKGLABEL].Get(); } + if (jsonObject[TOKENID].IsNumberInteger()) { + tokenId = jsonObject[TOKENID].Get(); + } } bundleName_ = DM_UI_BUNDLE_NAME; @@ -105,14 +110,28 @@ void DmDialogManager::ShowConfirmDialog(const std::string param) customDescriptionStr_ = customDescriptionStr; deviceType_ = deviceType; hostPkgLabel_ = hostPkgLabel; + tokenId_ = tokenId; ConnectExtension(); } void DmDialogManager::ShowPinDialog(const std::string param) { + std::string pinCode; + uint64_t tokenId = 0; bundleName_ = DM_UI_BUNDLE_NAME; abilityName_ = PIN_ABILITY_NAME; - pinCode_ = param; + JsonObject jsonObject(param); + if (!jsonObject.IsDiscarded()) { + if (jsonObject[PIN_CODE_KEY].IsNumberInteger()) { + pinCode = std::to_string(jsonObject[PIN_CODE_KEY].Get()); + } + if (jsonObject[TOKENID].IsNumberInteger()) { + tokenId = jsonObject[TOKENID].Get(); + } + } + + pinCode_ = pinCode; + tokenId_ = tokenId; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) ffrt::submit([]() { ConnectExtension(); }); #else @@ -127,7 +146,20 @@ void DmDialogManager::ShowPinDialog(const std::string param) void DmDialogManager::ShowInputDialog(const std::string param) { - targetDeviceName_ = param; + std::string targetDeviceName; + uint64_t tokenId = 0; + JsonObject jsonObject(param); + if (!jsonObject.IsDiscarded()) { + if (jsonObject[TAG_TARGET_DEVICE_NAME].IsString()) { + targetDeviceName = jsonObject[TAG_TARGET_DEVICE_NAME].Get(); + } + if (jsonObject[TOKENID].IsNumberInteger()) { + tokenId = jsonObject[TOKENID].Get(); + } + } + + targetDeviceName_ = targetDeviceName; + tokenId_ = tokenId; bundleName_ = DM_UI_BUNDLE_NAME; abilityName_ = INPUT_ABILITY_NAME; ConnectExtension(); @@ -201,7 +233,8 @@ void DmDialogManager::DialogAbilityConnection::OnAbilityConnectDone( param[TAG_TARGET_DEVICE_NAME] = DmDialogManager::GetTargetDeviceName(); param[TAG_HOST_PKGLABEL] = DmDialogManager::GetHostPkgLabel(); param["disableUpGesture"] = 1; - std::string paramStr = SafetyDump(param); + param[TOKENID] = DmDialogManager::GetTokenId(); + std::string paramStr = param.Dump(); data.WriteString16(Str8ToStr16(paramStr)); LOGI("show dm dialog is begin"); const uint32_t cmdCode = 1; diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index 273db6dfb..fc130c5dd 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -22,7 +22,6 @@ namespace OHOS { namespace DistributedHardware { -const char* TAG_REPLY = "REPLY"; const char* TAG_NET_ID = "NETID"; const char* TAG_TARGET = "TARGET"; const char* TAG_APP_OPERATION = "APPOPERATION"; @@ -43,35 +42,25 @@ const char* TAG_CRYPTO_NAME = "CRYPTONAME"; const char* TAG_CRYPTO_VERSION = "CRYPTOVERSION"; const char* TAG_IDENTICAL_ACCOUNT = "IDENTICALACCOUNT"; const char* TAG_ACCOUNT_GROUPID = "ACCOUNTGROUPID"; -const char* APP_THUMBNAIL = "appThumbnail"; const char* QR_CODE_KEY = "qrCode"; const char* TAG_AUTH_TOKEN = "authToken"; const char* NFC_CODE_KEY = "nfcCode"; const char* OLD_VERSION_ACCOUNT = "oldVersionAccount"; -const char* TAG_AUTH_FINISH = "isFinish"; const char* TAG_HAVE_CREDENTIAL = "haveCredential"; const char* TAG_PUBLICKEY = "publicKey"; const char* TAG_SESSIONKEY = "sessionKey"; -const char* TAG_BIND_LEVEL = "bindLevel"; -const char* TAG_LOCAL_USERID = "localUserId"; const char* TAG_BIND_TYPE_SIZE = "bindTypeSize"; const char* TAG_ISONLINE = "isOnline"; const char* TAG_AUTHED = "authed"; const char* TAG_LOCAL_ACCOUNTID = "localAccountId"; -const char* TAG_DMVERSION = "dmVersion"; const char* TAG_HOST_PKGNAME = "hostPkgname"; const char* TAG_TOKENID = "tokenId"; const char* TAG_HAVECREDENTIAL = "haveCredential"; const char* TAG_CONFIRM_OPERATION = "confirmOperation"; -const char* TAG_DATA = "data"; -const char* TAG_DATA_LEN = "dataLen"; const char* TAG_IMPORT_AUTH_CODE = "IMPORT_AUTH_CODE"; const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; -const char* TAG_EDITION = "edition"; -const char* TAG_BUNDLE_NAME = "bundleName"; const char* TAG_CRYPTIC_MSG = "encryptMsg"; -const char* TAG_PEER_BUNDLE_NAME = "PEER_BUNDLE_NAME"; const char* TAG_REMOTE_DEVICE_NAME = "REMOTE_DEVICE_NAME"; const char* TAG_SESSIONKEY_ID = "sessionKeyId"; diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 842e8ccba..14a873316 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -52,21 +52,6 @@ namespace OHOS { namespace DistributedHardware { -const int32_t AUTHENTICATE_TIMEOUT = 120; -const int32_t CONFIRM_TIMEOUT = 60; -const int32_t NEGOTIATE_TIMEOUT = 10; -const int32_t INPUT_TIMEOUT = 60; -const int32_t ADD_TIMEOUT = 10; -const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t WAIT_REQUEST_TIMEOUT = 10; -const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; -const int32_t CLONE_CONFIRM_TIMEOUT = 10; -const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; -const int32_t CLONE_ADD_TIMEOUT = 10; -const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; -const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; -const int32_t HML_SESSION_TIMEOUT = 10; const int32_t CANCEL_PIN_CODE_DISPLAY = 1; const int32_t DEVICE_ID_HALF = 2; const int32_t MAX_AUTH_TIMES = 3; @@ -79,24 +64,11 @@ const int32_t DM_AUTH_TYPE_MIN = 0; const int32_t AUTH_SESSION_SIDE_SERVER = 0; const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms const int32_t AUTH_DEVICE_TIMEOUT = 10; -const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; const int32_t ALREADY_BIND = 1; const int32_t STRTOLL_BASE_10 = 10; const int32_t MAX_PUT_SESSIONKEY_TIMEOUT = 100; //ms const int32_t SESSION_CLOSE_TIMEOUT = 2; -constexpr const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authenticate"; -constexpr const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; -constexpr const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; -constexpr const char* INPUT_TIMEOUT_TASK = "deviceManagerTimer:input"; -constexpr const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; -constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; -constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; -constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; -constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; -constexpr const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK = "deviceManagerTimer:waitSessionClose"; -constexpr const char* CLOSE_SESSION_TASK_SEPARATOR = "#"; - constexpr int32_t PROCESS_NAME_WHITE_LIST_NUM = 1; constexpr const static char* PROCESS_NAME_WHITE_LIST[PROCESS_NAME_WHITE_LIST_NUM] = { "com.example.myapplication", @@ -113,17 +85,7 @@ const std::map TASK_TIME_OUT_MAP = { { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } }; -constexpr const char* APP_OPERATION_KEY = "appOperation"; -constexpr const char* TARGET_PKG_NAME_KEY = "targetPkgName"; -constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; -constexpr const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; -constexpr const char* BUNDLE_NAME_KEY = "bundleName"; constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; -constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; -constexpr const char* DM_VERSION_5_0_2 = "5.0.2"; -constexpr const char* DM_VERSION_5_0_3 = "5.0.3"; -constexpr const char* DM_VERSION_5_0_4 = "5.0.4"; -constexpr const char* DM_VERSION_5_0_5 = "5.0.5"; std::mutex g_authFinishLock; DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, @@ -232,8 +194,8 @@ int32_t DmAuthManager::CheckAuthParamVaildExtra(const std::string &extra, const return ERR_DM_INPUT_PARA_INVALID; } - if (static_cast(bindLevel) == DEVICE && !IsAllowDeviceBind()) { - LOGE("not allowd device level bind bindlevel: %{public}d.", bindLevel); + if (static_cast(bindLevel) == USER && !IsAllowDeviceBind()) { + LOGE("not allowd user level bind bindlevel: %{public}d.", bindLevel); return ERR_DM_INPUT_PARA_INVALID; } return DM_OK; @@ -337,8 +299,8 @@ void DmAuthManager::ParseJsonObject(JsonObject &jsonObject) authRequestContext_->customDesc = DmLanguageManager::GetInstance(). GetTextBySystemLanguage(jsonObject[CUSTOM_DESCRIPTION_KEY].Get()); } - if (IsString(jsonObject, APP_THUMBNAIL)) { - authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL].Get(); + if (IsString(jsonObject, TAG_APP_THUMBNAIL2)) { + authRequestContext_->appThumbnail = jsonObject[TAG_APP_THUMBNAIL2].Get(); } CheckBindLevel(jsonObject, TAG_BIND_LEVEL, authRequestContext_->bindLevel); authRequestContext_->closeSessionDelaySeconds = 0; @@ -476,7 +438,7 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st LOGE("ReportDeleteTrustRelation failed"); } remoteDeviceId_ = udid; - if (static_cast(bindLevel) == DEVICE) { + if (static_cast(bindLevel) == USER) { DeleteGroup(pkgName, udid); } std::string extra = ""; @@ -529,11 +491,11 @@ int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string & return DM_OK; } } - if (static_cast(bindLevel) == DEVICE && offlineParam.leftAclNumber != 0) { + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber != 0) { LOGI("Unbind deivce-level, retain identical account bind type."); return DM_OK; } - if (static_cast(bindLevel) == DEVICE && offlineParam.leftAclNumber == 0) { + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber == 0) { LOGI("Unbind deivce-level, retain null."); hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); return DM_OK; @@ -550,7 +512,7 @@ int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::strin } char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - if (static_cast(bindLevel) == DEVICE) { + if (static_cast(bindLevel) == USER) { DeleteGroup(pkgName, udid); } return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra); @@ -1040,10 +1002,10 @@ void DmAuthManager::RespNegotiate(const int32_t &sessionId) remoteDeviceId_ = authResponseContext_->localDeviceId; authResponseContext_->networkId = softbusConnector_->GetLocalDeviceNetworkId(); authResponseContext_->targetDeviceName = softbusConnector_->GetLocalDeviceName(); - remoteVersion_ = ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition); + remoteVersion_ = AuthManagerBase::ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition); NegotiateRespMsg(remoteVersion_); if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= DEVICE && + (static_cast(authResponseContext_->bindLevel) >= USER && static_cast(authResponseContext_->bindLevel) <= APP)) { ProcRespNegotiateExt(sessionId); timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), @@ -1099,7 +1061,7 @@ void DmAuthManager::SendAuthRequest(const int32_t &sessionId) LOGI("SendAuthRequest dmversion %{public}s, level %{public}d", authResponseContext_->dmVersion.c_str(), authResponseContext_->bindLevel); if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= DEVICE && + (static_cast(authResponseContext_->bindLevel) >= USER && static_cast(authResponseContext_->bindLevel) <= APP)) { ProcessAuthRequestExt(sessionId); } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || @@ -1303,7 +1265,7 @@ int32_t DmAuthManager::StartAuthProcess(const int32_t &action) LOGE("ReportAuthConfirmBox failed"); } if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= DEVICE && + (static_cast(authResponseContext_->bindLevel) >= USER && static_cast(authResponseContext_->bindLevel) <= APP)) { return ConfirmProcessExt(action); } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || @@ -1801,7 +1763,7 @@ void DmAuthManager::ShowAuthInfoDialog(bool authDeviceError) jsonObj[PIN_CODE_KEY] = authResponseContext_->code; std::string authParam = SafetyDump(jsonObj); pincodeDialogEverShown_ = true; - DmDialogManager::GetInstance().ShowPinDialog(std::to_string(authResponseContext_->code)); + DmDialogManager::GetInstance().ShowPinDialog(authParam); } void DmAuthManager::ShowStartAuthDialog() @@ -1818,7 +1780,7 @@ void DmAuthManager::ShowStartAuthDialog() return; } if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= DEVICE && + (static_cast(authResponseContext_->bindLevel) >= USER && static_cast(authResponseContext_->bindLevel) <= APP)) { AuthDevice(pinCode); } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || @@ -1857,7 +1819,7 @@ int32_t DmAuthManager::ProcessPincode(int32_t pinCode) timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); } if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (static_cast(authResponseContext_->bindLevel) >= DEVICE && + (static_cast(authResponseContext_->bindLevel) >= USER && static_cast(authResponseContext_->bindLevel) <= APP)) { return AuthDevice(pinCode); } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || @@ -1918,35 +1880,28 @@ int32_t DmAuthManager::OnUserOperation(int32_t action, const std::string ¶ms case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: SetReasonAndFinish(ERR_DM_TIME_OUT, STATUS_DM_AUTH_DEFAULT); info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_TIME_OUT); - if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) { - LOGE("ReportAuthConfirmBox failed"); - } break; case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY, STATUS_DM_AUTH_DEFAULT); info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY); - if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) { - LOGE("ReportAuthInputPinBox failed"); - } break; case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: SetReasonAndFinish(ERR_DM_BIND_USER_CANCEL_ERROR, STATUS_DM_AUTH_DEFAULT); info.errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_BIND_USER_CANCEL_ERROR); - if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) { - LOGE("ReportAuthInputPinBox failed"); - } break; case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: - ProcessPincode(std::atoi(params.c_str())); - info.stageRes = static_cast(StageRes::STAGE_SUCC); - if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) { - LOGE("ReportAuthInputPinBox failed"); + if (ProcessPinCode(params) != DM_OK) { + return ERR_DM_INPUT_PARA_INVALID; } + info.stageRes = static_cast(StageRes::STAGE_SUCC); break; default: LOGE("this action id not support"); break; } + if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) { + LOGE("ReportAuthConfirmBox failed"); + } return DM_OK; } @@ -2052,7 +2007,7 @@ int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::str } int32_t DmAuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam) + const std::map &bindParam, int sessionId, int64_t logicalSessionId) { struct RadarInfo info = { .funcName = "AuthenticateDevice", @@ -2577,6 +2532,27 @@ int32_t DmAuthManager::GetSessionKeyIdSync(int64_t requestId) return keyid; } +char *DmAuthManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) +{ + LOGI("DmAuthManager::AuthDeviceRequest start."); + (void)requestId; + (void)reqParams; + JsonObject jsonObj; + int32_t pinCode = INVALID_PINCODE; + if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; + } else { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); + } + std::string deviceId = ""; + GetRemoteDeviceId(deviceId); + jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; + std::string jsonStr = SafetyDump(jsonObj); + char *buffer = strdup(jsonStr.c_str()); + return buffer; +} + void DmAuthManager::GetRemoteDeviceId(std::string &deviceId) { LOGI("GetRemoteDeviceId start."); @@ -2593,7 +2569,7 @@ void DmAuthManager::CompatiblePutAcl() Crypto::GetUdidHash(localUdid, reinterpret_cast(mUdidHash)); std::string localUdidHash = static_cast(mUdidHash); DmAclInfo aclInfo; - aclInfo.bindLevel = DEVICE; + aclInfo.bindLevel = USER; aclInfo.bindType = DM_POINT_TO_POINT; aclInfo.trustDeviceId = remoteDeviceId_; if (action_ == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { @@ -3009,21 +2985,6 @@ void DmAuthManager::HandleDeviceNotTrust(const std::string &udid) hiChainConnector_->DeleteAllGroupByUdid(udid); } -std::string DmAuthManager::ConvertSrcVersion(const std::string &version, const std::string &edition) -{ - std::string srcVersion = ""; - if (version == "" && edition != "") { - srcVersion = edition; - } else if (version == "" && edition == "") { - srcVersion = DM_VERSION_5_0_1; - } else if (version != "" && edition == "") { - srcVersion = version; - } - LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.", - version.c_str(), edition.c_str(), srcVersion.c_str()); - return srcVersion; -} - std::string DmAuthManager::ConvertSinkVersion(const std::string &version) { std::string sinkVersion = ""; @@ -3069,13 +3030,13 @@ int32_t DmAuthManager::GetBindLevel(int32_t bindLevel) int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); if (ret == DM_OK && CheckProcessNameInWhiteList(processName)) { - return DEVICE; + return USER; } #endif if (IsAllowDeviceBind()) { if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || - static_cast(bindLevel) < DEVICE) { - return DEVICE; + static_cast(bindLevel) < USER) { + return USER; } return bindLevel; } @@ -3145,7 +3106,7 @@ void DmAuthManager::SetProcessInfo() } else { LOGE("DMAuthManager::SetProcessInfo failed, state is invalid."); } - } else if (static_cast(authResponseContext_->bindLevel) == DEVICE || + } else if (static_cast(authResponseContext_->bindLevel) == USER || static_cast(authResponseContext_->bindLevel) == INVALIED_TYPE) { processInfo.pkgName = std::string(DM_PKG_NAME); processInfo.userId = authResponseContext_->localUserId; @@ -3380,5 +3341,19 @@ void DmAuthManager::CloseAuthSession(const int32_t sessionId) CHECK_NULL_VOID(softbusConnector_->GetSoftbusSession()); softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); } + +int32_t DmAuthManager::ProcessPinCode(const std::string &jsonStr) +{ + JsonObject jsonObject(jsonStr); + if (jsonObject.IsDiscarded()) { + LOGE("OnUserOperation jsonStr error"); + return ERR_DM_FAILED; + } + if (jsonObject.Contains(PIN_CODE_KEY) && jsonObject[PIN_CODE_KEY].IsString()) { + ProcessPincode(std::stoi(jsonObject[PIN_CODE_KEY].Get())); + return DM_OK; + } + return ERR_DM_FAILED; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp new file mode 100644 index 000000000..a12e25b2d --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -0,0 +1,1047 @@ +/* + * Copyright (c) 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 + +#include "app_manager.h" +#include "softbus_common.h" +#include "system_ability_definition.h" +#include "iservice_registry.h" +#include "parameter.h" +#include "deviceprofile_connector.h" +#include "multiple_user_connector.h" + +#include "dm_constants.h" +#include "dm_crypto.h" +#include "dm_random.h" +#include "dm_log.h" +#include "dm_timer.h" +#include "dm_radar_helper.h" +#include "dm_device_info.h" +#include "dm_anonymous.h" +#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 { +namespace DistributedHardware { +namespace { + +constexpr int32_t MIN_PIN_CODE = 100000; +constexpr int32_t MAX_PIN_CODE = 999999; + +int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr) +{ + if (!IsNumberString(delaySecondsStr)) { + LOGE("Invalid parameter, param is not number."); + return 0; + } + const int32_t closeSessionDelaySecondsMax = 10; + int32_t delaySeconds = std::atoi(delaySecondsStr.c_str()); + if (delaySeconds < 0 || delaySeconds > closeSessionDelaySecondsMax) { + LOGE("Invalid parameter, param out of range."); + return 0; + } + return delaySeconds; +} + +std::string GetBundleLable(const std::string &bundleName) +{ + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + LOGE("Get ability manager failed"); + return bundleName; + } + + sptr object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (object == nullptr) { + LOGE("object is NULL."); + return bundleName; + } + + sptr bms = iface_cast(object); + if (bms == nullptr) { + LOGE("bundle manager service is NULL."); + return bundleName; + } + + auto bundleResourceProxy = bms->GetBundleResourceProxy(); + if (bundleResourceProxy == nullptr) { + LOGE("GetBundleResourceProxy fail"); + return bundleName; + } + AppExecFwk::BundleResourceInfo resourceInfo; + auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName, + static_cast(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo); + if (result != ERR_OK) { + LOGE("GetBundleResourceInfo failed"); + return bundleName; + } + LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str()); + return resourceInfo.label; +} + +bool IsAllowDeviceBind(void) +{ + if (AppManager::GetInstance().IsSystemSA()) { + return true; + } + return false; +} + +int32_t CheckAuthParamVaildExtra(const std::string &extra) +{ + JsonObject jsonObject(extra); + if (jsonObject.IsDiscarded() || !jsonObject.Contains(TAG_BIND_LEVEL) || + !jsonObject[TAG_BIND_LEVEL].IsNumberInteger()) { + return DM_OK; + } + int32_t bindLevel = jsonObject[TAG_BIND_LEVEL].Get(); + if (static_cast(bindLevel) > APP || bindLevel < INVALID_TYPE) { + LOGE("bindlevel error %{public}d.", bindLevel); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (static_cast(bindLevel) == USER && !IsAllowDeviceBind()) { + LOGE("not allowd user level bind bindlevel: %{public}d.", bindLevel); + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +std::string ParseExtraFromMap(const std::map &bindParam) +{ + auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); + if (iter != bindParam.end()) { + return iter->second; + } + return ConvertMapToJsonString(bindParam); +} + +} // namespace + +bool AuthManager::IsHmlSessionType(const std::string &sessionType) +{ + return sessionType == CONN_SESSION_TYPE_HML; +} + +AuthManager::AuthManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) +{ + LOGI("DmAuthManager constructor"); + context_ = std::make_shared(); + context_->softbusConnector = softbusConnector; + context_->listener = listener; + context_->hiChainAuthConnector = hiChainAuthConnector; + context_->authUiStateMgr = std::make_shared(context_->listener); + context_->authenticationMap[AUTH_TYPE_PIN] = nullptr; + context_->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; + context_->authenticationMap[AUTH_TYPE_PIN_ULTRASONIC] = nullptr; + context_->authenticationMap[AUTH_TYPE_NFC] = nullptr; + context_->accesser.dmVersion = DM_VERSION_5_1_0; + context_->accessee.dmVersion = DM_VERSION_5_1_0; + context_->timer = std::make_shared(); + context_->authMessageProcessor = std::make_shared(); +} + +AuthManager::~AuthManager() +{ + if (context_ != nullptr) { + context_->isFinished = true; + context_->authStateMachine->Stop(); + context_->timer->DeleteAll(); + } + bindParam_.clear(); +} + +void AuthManager::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback) +{ + context_->cleanNotifyCallback = cleanNotifyCallback; + return; +} + +void AuthManager::SetAuthContext(std::shared_ptr context) +{ + this->context_ = context; +} + +std::shared_ptr AuthManager::GetAuthContext() +{ + return this->context_; +} + +int32_t AuthManager::ParseAuthType(const std::map &bindParam, int32_t &authType) +{ + auto iter = bindParam.find(PARAM_KEY_AUTH_TYPE); + if (iter == bindParam.end()) { + LOGE("AuthManager::ParseAuthType bind param key: %{public}s not exist.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + std::string authTypeStr = iter->second; + if (authTypeStr.empty()) { + LOGE("AuthManager::ParseAuthType bind param %{public}s is empty.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + if (authTypeStr.length() > 1) { + LOGE("AuthManager::ParseAuthType bind param %{public}s length is unsupported.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + if (!isdigit(authTypeStr[0])) { + LOGE("AuthManager::ParseAuthType bind param %{public}s fromat is unsupported.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + authType = std::atoi(authTypeStr.c_str()); + return DM_OK; +} + +int32_t AuthManager::GeneratePincode() +{ + LOGI("AuthManager::GeneratePincode start"); + context_->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); + return context_->pinCode; +} + +int32_t AuthManager::RegisterUiStateCallback(const std::string sessionName) +{ + LOGI("AuthManager::RegisterUiStateCallback start"); + if (context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::RegisterUiStateCallback context_->authUiStateMgr is null."); + return ERR_DM_FAILED; + } + context_->authUiStateMgr->RegisterUiStateCallback(sessionName); + return DM_OK; +} + +int32_t AuthManager::UnRegisterUiStateCallback(const std::string sessionName) +{ + LOGI("AuthManager::UnRegisterUiStateCallback start"); + if (context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::UnRegisterUiStateCallback context_->authUiStateMgr is null."); + return ERR_DM_FAILED; + } + context_->authUiStateMgr->UnRegisterUiStateCallback(sessionName); + return DM_OK; +} + +int32_t AuthManager::UnAuthenticateDevice(const std::string &sessionName, const std::string &udid, int32_t bindLevel) +{ + LOGI("AuthManager::UnAuthenticateDevice start"); + return ERR_DM_FAILED; +} + +int32_t AuthManager::ImportAuthCode(const std::string &sessionName, const std::string &authCode) +{ + if (authCode.empty() || sessionName.empty()) { + LOGE("ImportAuthCode failed, authCode or sessionName is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + context_->importAuthCode = authCode; + context_->importSessionName = sessionName; + + if (AuthSinkStatePinAuthComm::IsPinCodeValid(authCode)) { + context_->pinCode = std::stoi(authCode.c_str()); + } else { + AuthSinkStatePinAuthComm::GeneratePincode(context_); + } + LOGI("AuthManager::ImportAuthCode ok"); + return DM_OK; +} + +int32_t AuthManager::UnBindDevice(const std::string &sessionName, const std::string &udid, + int32_t bindLevel, const std::string &extra) +{ + LOGI("AuthManager::UnBindDevice start"); + return ERR_DM_FAILED; +} + +int32_t AuthManager::StopAuthenticateDevice(const std::string &sessionName) +{ + (void)sessionName; + LOGI("AuthManager::StopAuthenticateDevice start"); + + context_->reason = STOP_BIND; + if (context_->direction == DM_AUTH_SOURCE) { + context_->authStateMachine->TransitionTo(std::make_shared()); + } else { + context_->authStateMachine->TransitionTo(std::make_shared()); + } + return DM_OK; +} + +void AuthManager::OnScreenLocked() +{ + LOGI("AuthManager::OnScreenLocked start"); + if (DmAuthState::IsImportAuthCodeCompatibility(context_->authType)) { + LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", context_->authType); + return; + } + context_->reason = ERR_DM_BIND_USER_CANCEL; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); +} + +void AuthManager::HandleDeviceNotTrust(const std::string &udid) +{ + LOGI("AuthManager::HandleDeviceNotTrust start"); +} + +int32_t AuthManager::RegisterAuthenticationType(int32_t authenticationType) +{ + if (authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH && + authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + LOGE("Invalid parameter."); + return ERR_DM_INPUT_PARA_INVALID; + } + context_->authResult = static_cast(authenticationType); + return DM_OK; +} + +// Extract the local ACL for message parsing and bus usage. +// Without ACL, an empty string will be returned. +// JSON format string: {dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} +int32_t AuthManager::GetAclListStr(std::string &aclList) +{ + return context_->authMessageProcessor->GetAclListStr(context_, aclList); +} + +int32_t AuthManager::GetReason() +{ + return context_->reason; +} + +// Save the key +void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) +{ + LOGI("AuthSrcManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen); + if (context_ == nullptr || context_->authMessageProcessor == nullptr || context_->authStateMachine == nullptr) { + LOGE("AuthSrcManager::AuthDeviceSessionKey failed, auth context not initial."); + return; + } + if (requestId != context_->requestId) { + LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); + return; + } + int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); + if (ret != DM_OK) { + LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); + } + + context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); + LOGI("AuthSrcManager::AuthDeviceSessionKey leave."); +} + +char *AuthSrcManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) +{ + LOGI("AuthSrcManager::AuthDeviceRequest start"); + return nullptr; +} + +void AuthManager::SetAuthType(int32_t authType) +{ + context_->authType = (DmAuthType)authType; +} + +bool AuthManager::IsAuthTypeSupported(const int32_t &authType) +{ + if (context_->authenticationMap.find(authType) == context_->authenticationMap.end()) { + LOGE("IsAuthTypeSupported failed, authType is not supported."); + return false; + } + return true; +} + +bool AuthManager::IsAuthCodeReady(const std::string &sessionName) +{ + if (context_->importAuthCode.empty() || context_->importSessionName.empty()) { + LOGE("AuthManager::IsAuthCodeReady, auth code not ready with authCode %{public}s and sessionName %{public}s.", + context_->importAuthCode.c_str(), context_->importSessionName.c_str()); + return false; + } + if (sessionName != context_->importSessionName) { + LOGE("AuthManager::IsAuthCodeReady sessionName %{public}s not supported with import sessionName %{public}s.", + sessionName.c_str(), context_->importSessionName.c_str()); + return false; + } + return true; +} + +int32_t AuthManager::CheckAuthParamVaild(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("AuthManager::CheckAuthParamVaild start."); + if (authType < DM_AUTH_TYPE_MIN || authType > DM_AUTH_TYPE_MAX) { + LOGE("CheckAuthParamVaild failed, authType is illegal."); + return ERR_DM_AUTH_FAILED; + } + if (sessionName.empty() || deviceId.empty()) { + LOGE("AuthManager::CheckAuthParamVaild failed, sessionName is %{public}s, deviceId is %{public}s, extra is" + "%{public}s.", sessionName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + if (context_->listener == nullptr || context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::CheckAuthParamVaild listener or authUiStateMgr is nullptr."); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (!IsAuthTypeSupported(authType)) { + LOGE("AuthManager::CheckAuthParamVaild authType %{public}d not support.", authType); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, + ERR_DM_UNSUPPORTED_AUTH_TYPE); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_UNSUPPORTED_AUTH_TYPE; + } + + if (!context_->softbusConnector->HaveDeviceInMap(deviceId)) { + LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device."); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (DmAuthState::IsImportAuthCodeCompatibility(static_cast(authType)) && + (!IsAuthCodeReady(sessionName))) { + LOGE("Auth code not exist."); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +void AuthManager::ParseHmlInfoInJsonObject(const JsonObject &jsonObject) +{ + if (jsonObject[PARAM_KEY_CONN_SESSIONTYPE].IsString()) { + context_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); + LOGI("connSessionType %{public}s", context_->connSessionType.c_str()); + } + if (!IsHmlSessionType(context_->connSessionType)) { + return; + } + context_->connDelayCloseTime = HML_SESSION_TIMEOUT; + if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBoolean()) { + context_->hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get(); + LOGI("hmlEnable160M %{public}d", context_->hmlEnable160M); + } + if (jsonObject[PARAM_KEY_HML_ACTIONID].IsString()) { + std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); + if (IsNumberString(actionIdStr)) { + context_->hmlActionId = std::atoi(actionIdStr.c_str()); + } + if (context_->hmlActionId <= 0) { + context_->hmlActionId = 0; + } + LOGI("hmlActionId %{public}d", context_->hmlActionId); + } + + return; +} + +std::string AuthManager::GetBundleName(const JsonObject &jsonObject) +{ + if (!jsonObject.IsDiscarded() && jsonObject[BUNDLE_NAME_KEY].IsString()) { + return jsonObject[BUNDLE_NAME_KEY].Get(); + } + bool isSystemSA = false; + std::string bundleName; + AppManager::GetInstance().GetCallerName(isSystemSA, bundleName); + return bundleName; +} + +void AuthManager::ParseJsonObject(const JsonObject &jsonObject) +{ + if (jsonObject.IsDiscarded()) { + return; + } + + if (jsonObject[APP_OPERATION_KEY].IsString()) { + context_->appOperation = jsonObject[APP_OPERATION_KEY].Get(); + } + if (jsonObject[CUSTOM_DESCRIPTION_KEY].IsString()) { + context_->customData = jsonObject[CUSTOM_DESCRIPTION_KEY].Get(); + } + if (jsonObject[TAG_APP_THUMBNAIL2].IsString()) { + context_->appThumbnail = jsonObject[TAG_APP_THUMBNAIL2].Get(); + } + context_->connDelayCloseTime = 0; + if (jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].IsString()) { + std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].Get(); + context_->connDelayCloseTime = GetCloseSessionDelaySeconds(delaySecondsStr); + } + + context_->accesser.bundleName = GetBundleName(jsonObject); + context_->accessee.bundleName = context_->accesser.bundleName; + + if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { + context_->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); + } + if (jsonObject[TAG_PEER_DISPLAY_ID].IsNumberInteger()) { + context_->accessee.displayId = jsonObject[TAG_PEER_DISPLAY_ID].Get(); + } + if (jsonObject[TAG_LOCAL_USERID].IsNumberInteger()) { + context_->accesser.userId = jsonObject[TAG_LOCAL_USERID].Get(); + } else { + context_->accesser.userId = MultipleUserConnector::GetFirstForegroundUserId(); + } + + return; +} + +int32_t AuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId) +{ + int32_t ret = AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tokenId); + if (ret == DM_OK) { + return DM_OK; + } + ret = AppManager::GetInstance().GetHapTokenIdByName(userId, bundleName, 0, tokenId); + if (ret != DM_OK) { + LOGE("get tokenId by bundleName failed %{public}s", GetAnonyString(bundleName).c_str()); + } + return ret; +} + +void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("Get auth param with sessionName %{public}s and extra %{public}s.", sessionName.c_str(), extra.c_str()); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + context_->accesser.deviceId = std::string(localDeviceId); + context_->sessionName = sessionName; + context_->pkgLabel = GetBundleLable(sessionName); + context_->authType = (DmAuthType)authType; + context_->accesser.deviceName = context_->softbusConnector->GetLocalDeviceName(); + context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); + context_->accesser.isOnline = false; + uint32_t callingTokenId = 0; + MultipleUserConnector::GetCallingTokenId(callingTokenId); + context_->accesser.tokenId = static_cast(callingTokenId); + + context_->accessee.deviceId = deviceId; + context_->accessee.addr = deviceId; + JsonObject jsonObject(extra); + if (jsonObject.IsDiscarded()) { + LOGE("extra string not a json type."); + return; + } + ParseJsonObject(jsonObject); + context_->accesser.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context_->accesser.userId); +} + +void AuthManager::InitAuthState(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + auto iter = context_->authenticationMap.find(authType); + if (iter != context_->authenticationMap.end()) { + context_->authPtr = iter->second; + } + + context_->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + AUTHENTICATE_TIMEOUT, + [this] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context_, name); + }); + GetAuthParam(sessionName, authType, deviceId, extra); + context_->authStateMachine->TransitionTo(std::make_shared()); + LOGI("AuthManager::AuthenticateDevice complete"); + + return; +} + +int32_t AuthManager::AuthenticateDevice(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("AuthManager::AuthenticateDevice start auth type %{public}d.", authType); + SetAuthType(authType); + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + context_->processInfo.pkgName = sessionName; + context_->processInfo.userId = userId; + int32_t ret = CheckAuthParamVaild(sessionName, authType, deviceId, extra); + if (ret != DM_OK) { + LOGE("AuthManager::AuthenticateDevice failed, param is invaild."); + return ret; + } + ret = CheckAuthParamVaildExtra(extra); + if (ret != DM_OK) { + LOGE("CheckAuthParamVaildExtra failed, param is invaild."); + return ret; + } + context_->isAuthenticateDevice = true; + if (authType == AUTH_TYPE_CRE) { + LOGI("AuthManager::AuthenticateDevice for credential type, joinLNN directly."); + context_->softbusConnector->JoinLnn(deviceId, true); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, + "", STATUS_DM_AUTH_DEFAULT, DM_OK); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + DM_OK, STATUS_DM_AUTH_DEFAULT, ""); + return DM_OK; + } + InitAuthState(sessionName, authType, deviceId, extra); + return DM_OK; +} + +int32_t AuthManager::BindTarget(const std::string &sessionName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, int64_t logicalSessionId) +{ + int ret = DM_OK; + LOGI("AuthManager::BindTarget start. sessionName: %{public}s", sessionName.c_str()); + for (auto iter = bindParam.begin(); iter != bindParam.end(); iter++) { + LOGI("AuthManager::BindTarget para: %{public}s : %{public}s ", iter->first.c_str(), iter->second.c_str()); + } + + struct RadarInfo info = { + .funcName = "AuthenticateDevice", + .stageRes = static_cast(StageRes::STAGE_SUCC), + .bizState = static_cast(BizState::BIZ_STATE_END), + }; + if (!DmRadarHelper::GetInstance().ReportDiscoverUserRes(info)) { + LOGE("ReportDiscoverUserRes failed"); + } + if (sessionName.empty()) { + LOGE("AuthManager::BindTarget failed, sessionName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t authType = -1; + if (ParseAuthType(bindParam, authType) != DM_OK) { + LOGE("AuthManager::BindTarget failed, key: %{public}s error.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + context_->peerTargetId = targetId_; + bindParam_ = bindParam; + if (!targetId.deviceId.empty()) { + ret = AuthenticateDevice(sessionName, authType, targetId.deviceId, ParseExtraFromMap(bindParam)); + if (ret != DM_OK) { + return ret; + } + } else { + LOGE("AuthManager::BindTarget failed, targetId is error."); + return ERR_DM_INPUT_PARA_INVALID; + } + + context_->sessionId = sessionId; + context_->logicalSessionId = logicalSessionId; + context_->requestId = logicalSessionId; + context_->authStateMachine->TransitionTo(std::make_shared()); + info = { .funcName = "BindTarget" }; + info.channelId = sessionId; + DmRadarHelper::GetInstance().ReportAuthSendRequest(info); + return ret; +} + +AuthSinkManager::AuthSinkManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) + : AuthManager(softbusConnector, listener, hiChainAuthConnector) +{ + context_->direction = DM_AUTH_SINK; + context_->authStateMachine = std::make_shared(context_); +} + +void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); +} + +void AuthSinkManager::OnSessionClosed(int32_t sessionId) +{ + LOGI("AuthSrcManager::OnSessionClosed sessionId = %{public}d", sessionId); + context_->reason = ERR_DM_SESSION_CLOSED; + context_->authStateMachine->TransitionTo(std::make_shared()); +} + +void AuthSinkManager::OnDataReceived(int32_t sessionId, std::string message) +{ + context_->sessionId = sessionId; + int32_t ret = context_->authMessageProcessor->ParseMessage(context_, message); + if (ret != DM_OK) { + LOGE("OnDataReceived failed, parse input message error."); + } + + return; +} + +bool AuthSinkManager::GetIsCryptoSupport() +{ + return false; +} + +void AuthSinkManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) +{ + if (context_->hiChainAuthConnector == nullptr) { + LOGE("OnAuthDeviceDataReceived param is invalid"); + return; + } + + if (context_->sessionId != sessionId) { + LOGE("OnAuthDeviceDataReceived unmatched sessionId"); + return; + } + + JsonObject jsonObject(message); + if (jsonObject.IsDiscarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return; + } + if (!jsonObject[TAG_DATA].IsString() || !jsonObject[TAG_DATA_LEN].IsNumberInteger() || + !jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { + LOGE("Auth device data is error."); + return; + } + LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].Get()); + std::string authData = jsonObject[TAG_DATA].Get(); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + context_->hiChainAuthConnector->ProcessAuthData(context_->requestId, authData, osAccountId); + + return; +} + +void AuthManager::GetRemoteDeviceId(std::string &deviceId) +{ + deviceId = (context_->direction == DM_AUTH_SOURCE) ? context_->accessee.deviceId : context_->accesser.deviceId; + return; +} + +int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ms) +{ + LOGI("AuthSinkManager::OnUserOperation start."); + if (context_ == nullptr || context_->authStateMachine == nullptr) { + LOGE("OnUserOperation: Authenticate is not start"); + return ERR_DM_AUTH_NOT_START; + } + + switch (action) { + case USER_OPERATION_TYPE_CANCEL_AUTH: + case USER_OPERATION_TYPE_ALLOW_AUTH: + case USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS: + context_->authResult = static_cast(action); + context_->reply = USER_OPERATION_TYPE_ALLOW_AUTH; + if (action == USER_OPERATION_TYPE_CANCEL_AUTH) { + LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_AUTH."); + context_->reply = USER_OPERATION_TYPE_CANCEL_AUTH; + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); + break; + case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: + LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT."); + context_->authResult = USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT; + context_->reason = ERR_DM_TIME_OUT; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + break; + case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: + LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY."); + context_->authResult = USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY; + context_->reason = ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + break; + default: + LOGE("this action id not support"); + break; + } + LOGI("AuthSinkManager::OnUserOperation leave."); + return DM_OK; +} + +AuthSrcManager::AuthSrcManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) + : AuthManager(softbusConnector, listener, hiChainAuthConnector) +{ + context_->direction = DM_AUTH_SOURCE; + context_->authStateMachine = std::make_shared(context_); +} + +void AuthSrcManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); +} + +void AuthSrcManager::OnSessionClosed(int32_t sessionId) +{ + LOGI("AuthSrcManager::OnSessionClosed sessionId = %{public}d", sessionId); + context_->reason = ERR_DM_SESSION_CLOSED; + context_->authStateMachine->TransitionTo(std::make_shared()); +} + +void AuthSrcManager::OnDataReceived(int32_t sessionId, std::string message) +{ + context_->sessionId = sessionId; + int32_t ret = context_->authMessageProcessor->ParseMessage(context_, message); + if (ret != DM_OK) { + LOGE("OnDataReceived failed, parse input message error."); + } + + return; +} + +bool AuthSrcManager::GetIsCryptoSupport() +{ + return false; +} + +void AuthSrcManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) +{ + if (context_->hiChainAuthConnector == nullptr) { + LOGE("OnAuthDeviceDataReceived param is invalid"); + return; + } + + if (context_->sessionId != sessionId) { + LOGE("OnAuthDeviceDataReceived unmatched sessionId"); + return; + } + + JsonObject jsonObject(message); + if (jsonObject.IsDiscarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return; + } + if (!jsonObject[TAG_DATA].IsNumberInteger() || !jsonObject[TAG_DATA_LEN].IsNumberInteger() || + !jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { + LOGE("Auth device data is error."); + return; + } + LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].Get()); + std::string authData = jsonObject[TAG_DATA].Get(); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + context_->hiChainAuthConnector->ProcessAuthData(context_->requestId, authData, osAccountId); + + return; +} + +int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶ms) +{ + LOGI("AuthSrcManager::OnUserOperation start."); + if (context_ == nullptr || context_->authStateMachine == nullptr) { + LOGE("OnUserOperation: Authenticate is not start"); + return ERR_DM_AUTH_NOT_START; + } + + switch (action) { + case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: + LOGE("AuthSrcManager OnUserOperation user cancel"); + context_->pinInputResult = USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT; + context_->reason = ERR_DM_BIND_USER_CANCEL_ERROR; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + break; + case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: + LOGE("AuthSrcManager OnUserOperation user input done"); + context_->pinInputResult = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; + { + JsonObject jsonObject(params); + if (jsonObject.IsDiscarded()) { + LOGE("OnUserOperation jsonStr error"); + return ERR_DM_INPUT_PARA_INVALID; + } + if (jsonObject[PIN_CODE_KEY].IsString()) { + context_->pinCode = std::stoi(jsonObject[PIN_CODE_KEY].Get()); + } + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); + break; + default: + LOGE("this action id not support"); + break; + } + LOGI("AuthSrcManager::OnUserOperation leave."); + return DM_OK; +} + +void AuthSrcManager::AuthDeviceError(int64_t requestId, int32_t errorCode) +{ + LOGI("AuthSrcManager::AuthDeviceError start."); + auto curState = context_->authStateMachine->GetCurState(); + if (curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE || + curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE || + curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE) { + LOGI("AuthSrcManager::AuthDeviceError Auth pin err."); + if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { + context_->inputPinAuthFailTimes++; + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); + context_->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGI("AuthSrcManager::AuthDeviceError unexpected err."); + context_->reason = errorCode; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + } + LOGI("AuthSrcManager::AuthDeviceError leave."); +} + +void AuthSinkManager::AuthDeviceError(int64_t requestId, int32_t errorCode) +{ + LOGI("AuthSinkManager::AuthDeviceError start."); + auto curState = context_->authStateMachine->GetCurState(); + if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE || + curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE) { + LOGI("AuthSrcManager::AuthDeviceError Auth pin err."); + if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { + context_->inputPinAuthFailTimes++; + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); + context_->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGI("AuthSinkManager::AuthDeviceError unexpected err."); + context_->reason = errorCode; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + } + LOGI("AuthSinkManager::AuthDeviceError leave."); +} + +bool AuthSrcManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) +{ + LOGI("AuthSrcManager::AuthDeviceTransmit start."); + // check request id first + if (requestId != context_->requestId) { + LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64"is error.", requestId); + return false; + } + + context_->transmitData = std::string(reinterpret_cast(data), dataLen); + context_->authStateMachine->NotifyEventFinish(ON_TRANSMIT); + LOGI("AuthSrcManager::AuthDeviceTransmit leave."); + return true; +} + +bool AuthSinkManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) +{ + LOGI("AuthSinkManager::AuthDeviceTransmit start."); + // check request id first + if (requestId != context_->requestId) { + LOGE("AuthSinkManager::onTransmit requestId %{public}" PRId64"is error.", requestId); + return false; + } + + context_->transmitData = std::string(reinterpret_cast(data), dataLen); + context_->authStateMachine->NotifyEventFinish(ON_TRANSMIT); + LOGI("AuthSinkManager::AuthDeviceTransmit leave."); + return true; +} + +void AuthSrcManager::AuthDeviceFinish(int64_t requestId) +{ + LOGI("AuthSrcManager::AuthDeviceFinish start."); + context_->authStateMachine->NotifyEventFinish(ON_FINISH); + // Perform business processing based on the current state + DmAuthStateType curState = context_->authStateMachine->GetCurState(); + switch (curState) { + case DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE: + // ON_FINISH event occurs, start credential exchange + context_->authStateMachine->TransitionTo(std::make_shared()); + break; + default: + break; + } + LOGI("AuthSrcManager::AuthDeviceFinish leave."); +} + +void AuthSinkManager::AuthDeviceFinish(int64_t requestId) +{ + LOGI("AuthSinkManager::AuthDeviceFinish start."); + context_->authStateMachine->NotifyEventFinish(ON_FINISH); + LOGI("AuthSinkManager::AuthDeviceFinish leave."); +} + +void AuthSinkManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) +{ + LOGI("AuthSrcManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen); + if (context_ == nullptr || context_->authMessageProcessor == nullptr || context_->authStateMachine == nullptr) { + LOGE("AuthSrcManager::AuthDeviceSessionKey failed, auth context not initial."); + return; + } + if (requestId != context_->requestId) { + LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); + return; + } + int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); + if (ret != DM_OK) { + LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); + } + + context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); +} + +char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) +{ + LOGI("AuthSrcManager::AuthDeviceRequest start"); + (void)requestId; + (void)reqParams; + JsonObject jsonObj; + + DmAuthStateType curState = context_->authStateMachine->GetCurState(); + if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE) { + int32_t pinCode = INVALID_PINCODE; + if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; + } else { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); + } + } else if (curState == DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE) { + if (context_->isOnline) { // Non-first time certification + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_CRED_ID] = context_->accessee.transmitCredentialId; + } else if (!context_->isAppCredentialVerified) { // First-time authentication && appCred auth + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_CRED_ID] = context_->accessee.transmitCredentialId; + } else { // First-time authentication && User credential authentication + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_CRED_ID] = context_->accessee.lnnCredentialId; + } + } + jsonObj[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); + std::string jsonStr = jsonObj.Dump(); + char *buffer = strdup(jsonStr.c_str()); + return buffer; +} + +int32_t AuthManager::GetPinCode(int32_t &code) +{ + if (context_ == nullptr) { + LOGE("AuthManager failed to GetPinCode because context_ is nullptr"); + return ERR_DM_FAILED; + } + LOGI("GetPinCode called."); + code = context_->pinCode; + return DM_OK; +} + +// Reacquire BindParams to rebuild the link, generally used when switching between old and new protocol objects +void AuthManager::GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam) +{ + pkgName = context_->sessionName; + targetId = targetId_; + bindParam = bindParam_; + + LOGI("AuthManager::GetBindTargetParams get pkgName %{public}s to reuse", pkgName.c_str()); + return; +} + +void AuthManager::SetBindTargetParams(const PeerTargetId &targetId) +{ + targetId_ = targetId; + LOGI("AuthManager::SetBindTargetParams set targetId to reuse"); + return; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp new file mode 100644 index 000000000..6acca94f1 --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -0,0 +1,156 @@ +/* + * Copyright (c) 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 +#include + +#include "auth_manager.h" +#include "deviceprofile_connector.h" +#include "dm_auth_context.h" +#include "dm_auth_state.h" +#include "dm_auth_state_machine.h" +#include "dm_constants.h" +#include "dm_crypto.h" +#include "multiple_user_connector.h" + +namespace OHOS { +namespace DistributedHardware { + +const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms + +// Received 180 synchronization message, send 190 message +int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkDataSyncState::Action start"); + // Check if the quadruple of the ciphertext phase and the plaintext phase are the same, + // and if the bindlevel at both ends is the same. If not, end directly. + if (!IsQuadrupleAndBindLevelSame(context)) { + LOGE("data between two stages different, stop auth"); + return DM_OK; + } + // Query the ACL of the sink end. + std::vector sinkAclList = GetAclList(context); + // Compare the ACLs at both ends. + for (auto &sinkAcl : sinkAclList) { + bool res = context->authMessageProcessor->ChecksumAcl(sinkAcl, + context->accesser.accesserStrList, context->accesser.accesseeStrList); + if (res) { + continue; + } + SyncAclList(context, sinkAcl.GetAccessee().GetAccesseeUserId(), + sinkAcl.GetAccessee().GetAccesseeCredentialIdStr(), + sinkAcl.GetAccessee().GetAccesseeSessionKeyId(), sinkAcl.GetAccessControlId()); + } + // Synchronize the local SP information, the format is uncertain, not done for now + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_DATA_SYNC, context); + LOGI("AuthSinkDataSyncState::Action ok"); + return DM_OK; +} + +DmAuthStateType AuthSinkDataSyncState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE; +} + +// Received 190 message, sent 200 message +int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcDataSyncState::Action start"); + + if (NeedAgreeAcl(context)) { + // Check if the quadruple of the ciphertext phase and the plaintext phase are the same. If not, end directly. + if (!IsQuadrupleAndBindLevelSame(context)) { + LOGE("data between two stages different, stop auth"); + return DM_OK; + } + // Query the ACL of the sink end. + std::vector srcAclList = GetAclList(context); + // Compare the ACLs at both ends. + for (auto &srcAcl : srcAclList) { + bool res = context->authMessageProcessor->ChecksumAcl(srcAcl, + context->accessee.accesserStrList, context->accessee.accesseeStrList); + if (res) { + continue; + } + SyncAclList(context, srcAcl.GetAccesser().GetAccesserUserId(), + srcAcl.GetAccesser().GetAccesserCredentialIdStr(), + srcAcl.GetAccesser().GetAccesserSessionKeyId(), srcAcl.GetAccessControlId()); + } + // Save this acl + SetAclInfo(context); + context->authMessageProcessor->PutAccessControlList(context, context->accesser, context->accessee.deviceId); + // Synchronize the local SP information, the format is uncertain, not done for now + } + + // Trigger networking + if (!context->accesser.isOnline) { + char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetUdidHash(context->accessee.deviceId, reinterpret_cast(udidHashTmp)) != DM_OK) { + LOGE("AuthSrcDataSyncState joinLnn get udidhash by udid: %{public}s failed", + context->accessee.deviceId.c_str()); + return ERR_DM_FAILED; + } + std::string peerUdidHash = std::string(udidHashTmp); + context->softbusConnector->JoinLNNBySkId(context->sessionId, context->accesser.transmitSessionKeyId, + context->accessee.transmitSessionKeyId, context->accessee.addr, peerUdidHash); + } + context->reason = DM_OK; + context->reply = DM_OK; + context->state = static_cast(GetStateType()); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_REQ_FINISH, context); + LOGI("AuthSrcDataSyncState::Action ok"); + return DM_OK; +} + +DmAuthStateType AuthSrcDataSyncState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE; +} + +// Received 200 end message, send 201 +int32_t AuthSinkFinishState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkFinishState::Action start"); + context->state = static_cast(GetStateType()); + SinkFinish(context); + LOGI("AuthSinkFinishState::Action ok"); + context->cleanNotifyCallback(context->logicalSessionId); + return DM_OK; +} + +DmAuthStateType AuthSinkFinishState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_FINISH_STATE; +} + +// Received 201 end message +int32_t AuthSrcFinishState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcFinishState::Action start"); + if (context->reason != DM_OK) { + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_REQ_FINISH, context); + } + SourceFinish(context); + LOGI("AuthSrcFinishState::Action ok"); + context->cleanNotifyCallback(context->logicalSessionId); + return DM_OK; +} + +DmAuthStateType AuthSrcFinishState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_FINISH_STATE; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp new file mode 100644 index 000000000..dfadeafa5 --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -0,0 +1,738 @@ +/* + * Copyright (c) 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 "auth_manager.h" +#include "access_control_profile.h" +#include "deviceprofile_connector.h" +#include "distributed_device_profile_errors.h" +#include "dm_anonymous.h" +#include "dm_auth_context.h" +#include "dm_auth_state.h" +#include "dm_auth_state_machine.h" +#include "dm_crypto.h" +#include "dm_dialog_manager.h" +#include "dm_log.h" +#include "dm_negotiate_process.h" +#include "dm_softbus_cache.h" + +namespace OHOS { +namespace DistributedHardware { + +constexpr const char* TAG_CRED_ID = "credId"; +constexpr const char* TAG_CUSTOM_DESCRIPTION = "CUSTOMDESC"; +constexpr const char* TAG_LOCAL_DEVICE_TYPE = "LOCALDEVICETYPE"; +constexpr const char* TAG_REQUESTER = "REQUESTER"; +constexpr const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; +constexpr const char* UNVALID_CREDTID = "invalidCredId"; +// authType fallback table +using FallBackKey = std::pair; // accessee.bundleName, authType +static std::map g_pinAuthTypeFallBackMap = { + {{"CastEngineService", DmAuthType::AUTH_TYPE_NFC}, DmAuthType::AUTH_TYPE_PIN}, +}; +// Maximum number of recursive lookups +constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; + +DmAuthStateType AuthSrcConfirmState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CONFIRM_STATE; +} + +void AuthSrcConfirmState::NegotiateCredential(std::shared_ptr context, JsonObject &credTypeNegoResult) +{ + CHECK_NULL_VOID(context); + JsonObject accesseeCredTypeList; + accesseeCredTypeList.Parse(context->accessee.credTypeList); + JsonObject accesserCredTypeList; + accesserCredTypeList.Parse(context->accesser.credTypeList); + LOGI("yangwei accesseeCredTypeList %{public}s, accesserCredTypeList %{public}s.", + accesseeCredTypeList.Dump().c_str(), accesserCredTypeList.Dump().c_str()); + if (accesseeCredTypeList.IsDiscarded() || accesserCredTypeList.IsDiscarded()) { + LOGE("CredTypeList invalid."); + return; + } + if (accesseeCredTypeList.Contains("identicalCredType") && accesserCredTypeList.Contains("identicalCredType")) { + LOGI("have identical credential."); + credTypeNegoResult["identicalCredType"] = DM_IDENTICAL_ACCOUNT; + } + if (accesseeCredTypeList.Contains("shareCredType") && accesserCredTypeList.Contains("shareCredType")) { + LOGI("have share credential."); + credTypeNegoResult["shareCredType"] = DM_SHARE; + } + if (accesseeCredTypeList.Contains("pointTopointCredType") && accesserCredTypeList.Contains("pointTopointCredType")) { + LOGI("have point_to_point credential."); + credTypeNegoResult["pointTopointCredType"] = DM_POINT_TO_POINT; + } + if (accesseeCredTypeList.Contains("lnnCredType") && accesserCredTypeList.Contains("lnnCredType")) { + LOGI("have lnn credential."); + credTypeNegoResult["lnnCredType"] = DM_LNN; + context->accesser.isGenerateLnnCredential = false; + } +} + +void AuthSrcConfirmState::NegotiateAcl(std::shared_ptr context, JsonObject &aclNegoResult) +{ + CHECK_NULL_VOID(context); + JsonObject accesseeAclList; + accesseeAclList.Parse(context->accessee.aclList); + JsonObject accesserAclList; + accesserAclList.Parse(context->accesser.aclList); + LOGI("yangwei accesseeAclList %{public}s, accesserAclList %{public}s.", + accesseeAclList.Dump().c_str(), accesserAclList.Dump().c_str()); + if (accesseeAclList.IsDiscarded() || accesserAclList.IsDiscarded()) { + LOGE("aclList invalid."); + return; + } + if (accesseeAclList.Contains("identicalAcl") && accesserAclList.Contains("identicalAcl")) { + LOGI("have identical acl."); + aclNegoResult["identicalAcl"] = DM_IDENTICAL_ACCOUNT; + context->accesser.isAuthed = true; + } + if (accesseeAclList.Contains("shareCredType") && accesserAclList.Contains("shareCredType")) { + LOGI("have share acl."); + aclNegoResult["shareAcl"] = DM_SHARE; + context->accesser.isAuthed = true; + } + if (accesseeAclList.Contains("pointTopointAcl") && accesserAclList.Contains("pointTopointAcl")) { + LOGI("have point_to_point acl."); + aclNegoResult["pointTopointAcl"] = DM_POINT_TO_POINT; + context->accesser.isAuthed = true; + } + if (accesseeAclList.Contains("lnnAcl") && accesserAclList.Contains("lnnAcl")) { + LOGI("have lnn acl."); + aclNegoResult["lnnAcl"] = DM_LNN; + context->accesser.isPutLnnAcl = false; + } +} + +void AuthSrcConfirmState::GetSrcCredType(std::shared_ptr context, + JsonObject &credInfo, JsonObject &credTypeJson) +{ + CHECK_NULL_VOID(context); + std::vector deleteCredInfo; + for (const auto &item : credInfo.Items()) { + LOGI("yangwei credInfo %{public}s.", item.Dump().c_str()); + std::string key = item.Key(); + if (!item.Contains(key) || !item[key].IsObject() || !item[key].Contains(FILED_CRED_TYPE) || + !item[key][FILED_CRED_TYPE].IsNumberInteger()) { + deleteCredInfo.push_back(key); + continue; + } + int32_t credType = item[key][FILED_CRED_TYPE].Get(); + LOGI("credType %{public}d.", credType); + if (credType == DM_IDENTICAL_ACCOUNT) { + credTypeJson["identicalCredType"] = credType; + } else if (credType == DM_SHARE) { + credTypeJson["shareCredType"] = credType; + } else if (credType == DM_POINT_TO_POINT) { + credTypeJson["pointTopointCredType"] = credType; + } else if (credType == DM_LNN) { + credTypeJson["lnnCredType"] = credType; + } else { + continue; + } + context->accesser.credentialInfos[credType] = item.Dump(); + } + for (const auto &item : deleteCredInfo) { + credInfo.Erase(item); + } +} + +void AuthSrcConfirmState::GetSrcAclInfo(std::shared_ptr context, + JsonObject &credInfo, JsonObject &aclInfo) +{ + CHECK_NULL_VOID(context); + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + for (const auto &item : profiles) { + std::string trustDeviceId = item.GetTrustDeviceId(); + std::string trustDeviceIdHash = Crypto::Sha256(trustDeviceId); + if (trustDeviceIdHash != context->accessee.deviceIdHash) { + LOGE("Acl trust deviceId %{public}s hash %{public}s, not equal accesser deviceId %{public}s.", + GetAnonyString(trustDeviceId).c_str(), GetAnonyString(trustDeviceIdHash).c_str(), + GetAnonyString(context->accesser.deviceIdHash).c_str()); + continue; + } + int32_t bindType = item.GetBindType(); + switch (bindType) { + case DM_IDENTICAL_ACCOUNT: + if (IdenticalAccountAclCompare(context, item.GetAccesser(), item.GetAccessee())) { + aclInfo["identicalAcl"] = DM_IDENTICAL_ACCOUNT; + context->accesser.aclProfiles[DM_IDENTICAL_ACCOUNT] = item; + } + break; + case DM_SHARE: + if (ShareAclCompare(context, item.GetAccesser(), item.GetAccessee()) && + CheckCredIdInAcl(item, credInfo, bindType)) { + aclInfo["shareAcl"] = bindType; + context->accesser.aclProfiles[DM_SHARE] = item; + } + break; + case DM_POINT_TO_POINT: + // application + if (Point2PointAclCompare(context, item.GetAccesser(), item.GetAccessee()) && + CheckCredIdInAcl(item, credInfo, bindType)) { + aclInfo["pointTopointAcl"] = bindType; + context->accesser.aclProfiles[DM_POINT_TO_POINT] = item; + break; + } + // lnn + if (LnnAclCompare(context, item.GetAccesser(), item.GetAccessee()) && + CheckCredIdInAcl(item, credInfo, DM_LNN) && item.GetBindLevel() == USER) { + aclInfo["lnnAcl"] = DM_LNN; + context->accesser.aclProfiles[DM_LNN] = item; + break; + } + default: + LOGE("invalid bindType %{public}d.", bindType); + break; + } + } +} + +bool AuthSrcConfirmState::CheckCredIdInAcl(const DistributedDeviceProfile::AccessControlProfile &profile, + JsonObject &credInfo, uint32_t bindType) +{ + std::string credId = std::to_string(profile.GetAccesser().GetAccesserCredentialId()); + if (!credInfo.Contains(credId)) { + LOGE("credInfoJson not contain credId %{public}s.", credId.c_str()); + DeviceProfileConnector::GetInstance().DeleteAccessControlById(profile.GetAccessControlId()); + return false; + } + if (credInfo.Contains(credId) && (!credInfo[credId].IsObject() || !credInfo[credId].Contains(FILED_CRED_TYPE) || + !credInfo[credId][FILED_CRED_TYPE].IsNumberInteger())) { + LOGE("credId %{public}s contain credInfoJson invalid.", credId.c_str()); + DeviceProfileConnector::GetInstance().DeleteAccessControlById(profile.GetAccessControlId()); + credInfo.Erase(credId); + return false; + } + bool checkResult = false; + switch (bindType) { + LOGI("bindType %{public}d.", bindType); + case DM_IDENTICAL_ACCOUNT: + case DM_SHARE: + case DM_LNN: + if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { + checkResult = true; + } + break; + case DM_POINT_TO_POINT: + if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { + std::vector appList; + credInfo[credId][FILED_AUTHORIZED_APP_LIST].Get(appList); + if (std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[0] && + std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[1]) { + checkResult = true; + } else { + DeviceProfileConnector::GetInstance().DeleteAccessControlById(profile.GetAccessControlId()); + } + } + break; + default: + break; + } + return checkResult; +} + +bool AuthSrcConfirmState::IdenticalAccountAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + return accesser.GetAccesserDeviceId() == context->accesser.deviceId && + accesser.GetAccesserUserId() == context->accesser.userId && + Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash && + Crypto::Sha256(std::to_string(accessee.GetAccesseeUserId())) == context->accessee.userIdHash; +} + +bool AuthSrcConfirmState::ShareAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + return accesser.GetAccesserDeviceId() == context->accesser.deviceId && + accesser.GetAccesserUserId() == context->accesser.userId && + Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash && + Crypto::Sha256(std::to_string(accessee.GetAccesseeUserId())) == context->accessee.userIdHash; +} + +bool AuthSrcConfirmState::Point2PointAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + return accesser.GetAccesserDeviceId() == context->accesser.deviceId && + accesser.GetAccesserUserId() == context->accesser.userId && + accesser.GetAccesserAccountId() == context->accesser.accountId && + accesser.GetAccesserTokenId() == context->accesser.tokenId && + Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash && + Crypto::Sha256(std::to_string(accessee.GetAccesseeUserId())) == context->accessee.userIdHash && + Crypto::Sha256(accessee.GetAccesseeAccountId()) == context->accessee.accountIdHash && + Crypto::Sha256(std::to_string(accessee.GetAccesseeTokenId())) == context->accessee.tokenIdHash; +} + +bool AuthSrcConfirmState::LnnAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + return accesser.GetAccesserDeviceId() == context->accesser.deviceId && + accesser.GetAccesserUserId() == context->accesser.userId && + accesser.GetAccesserAccountId() == context->accesser.accountId && + accesser.GetAccesserTokenId() == 0 && accesser.GetAccesserBundleName() == "" && + Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash && + Crypto::Sha256(std::to_string(accessee.GetAccesseeUserId())) == context->accessee.userIdHash && + Crypto::Sha256(accessee.GetAccesseeAccountId()) == context->accessee.accountIdHash && + accessee.GetAccesseeTokenId() == 0 && accessee.GetAccesseeBundleName() == ""; +} + +void AuthSrcConfirmState::GetSrcCredentialInfo(std::shared_ptr context, JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + // get identical credential + if (context->accesser.accountIdHash == context->accessee.accountIdHash) { + GetIdenticalCredentialInfo(context, credInfo); + } + // get share credential + if (context->accesser.accountIdHash != context->accessee.accountIdHash && + context->accesser.accountIdHash != "ohosAnonymousUid" && + context->accessee.accountIdHash != "ohosAnonymousUid") { + GetShareCredentialInfo(context, credInfo); + GetP2PCredentialInfo(context, credInfo); + } + // get point_to_point credential + if (context->accesser.accountIdHash == "ohosAnonymousUid" || + context->accessee.accountIdHash == "ohosAnonymousUid") { + GetP2PCredentialInfo(context, credInfo); + } + JsonObject credTypeJson; + std::vector deleteCredInfo; + for (auto &item : credInfo.Items()) { // id1:json1, id2:json2, id3:json3 + LOGI("yangwei pre credInfo %{public}s.", item.Dump().c_str()); + std::string key = item.Key(); + if (!item.Contains(key) || !item[key].IsObject()) { + LOGE("credInfo %{public}s invalid.", item.Dump().c_str()); + deleteCredInfo.push_back(key); + continue; + } + JsonItemObject credInfoTemp = item[key]; + uint32_t credType = GetCredentialType(context, credInfoTemp); + if (credType == DM_INVALIED_BINDTYPE || !credInfoTemp.Contains(FILED_CRED_TYPE) || + !credInfoTemp[FILED_CRED_TYPE].IsNumberInteger()) { + deleteCredInfo.push_back(key); + continue; + } + item[key][FILED_CRED_TYPE] = credType; + LOGI("yangwei after credInfo %{public}s.", item.Dump().c_str()); + } + for (const auto &item : deleteCredInfo) { + credInfo.Erase(item); + } +} + +uint32_t AuthSrcConfirmState::GetCredentialType(std::shared_ptr context, + const JsonItemObject &credInfo) +{ + CHECK_NULL_RETURN(context, DM_INVALIED_BINDTYPE); + if (!credInfo.Contains(FILED_CRED_TYPE) || !credInfo[FILED_CRED_TYPE].IsNumberInteger() || + !credInfo.Contains(FILED_AUTHORIZED_SCOPE) || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumberInteger() || + !credInfo.Contains(FILED_SUBJECT) || !credInfo[FILED_SUBJECT].IsNumberInteger()) { + LOGE("credType or authorizedScope invalid."); + return DM_INVALIED_BINDTYPE; + } + int32_t credType = credInfo[FILED_CRED_TYPE].Get(); + int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); + int32_t subject = credInfo[FILED_SUBJECT].Get(); + std::vector appList; + credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); + if (credType == ACCOUNT_RELATED && authorizedScope == SCOPE_USER) { + return DM_IDENTICAL_ACCOUNT; + } + if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && + context->direction == DM_AUTH_SOURCE && subject == SUBJECT_PRIMARY) { + return DM_SHARE; + } + if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && + context->direction == DM_AUTH_SINK && subject == SUBJECT_SECONDARY) { + return DM_SHARE; + } + if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { + return DM_POINT_TO_POINT; + } + if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_USER && appList.empty()) { + return DM_LNN; + } + return DM_INVALIED_BINDTYPE; +} + +bool AuthSrcConfirmState::HaveSameTokenId(std::shared_ptr context, + const std::vector &tokenList) +{ + // Store the token of src and sink. The size must be 2. + if (tokenList.size() != 2) { + LOGE("HaveSameTokenId invalid tokenList size."); + return false; + } + + // tokenIdList = [srcTokenId, sinkTokenId] + std::string srcTokenIdHash = Crypto::Sha256(tokenList[0]); + std::string sinkTokenIdHash = Crypto::Sha256(tokenList[1]); + + return (srcTokenIdHash == context->accesser.tokenIdHash) && + (sinkTokenIdHash == context->accessee.tokenIdHash); +} + +void AuthSrcConfirmState::GetIdenticalCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID] = context->accesser.deviceId; + queryParams[FILED_USER_ID] = context->accesser.accountId; + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_RELATED; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accesser.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} + +void AuthSrcConfirmState::GetShareCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID_HASH] = context->accessee.deviceIdHash; + queryParams[FILED_PEER_USER_SPACE_ID] = std::to_string(context->accessee.userId); + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accesser.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} + +void AuthSrcConfirmState::GetP2PCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID_HASH] = context->accessee.deviceIdHash; + queryParams[FILED_PEER_USER_SPACE_ID] = std::to_string(context->accessee.userId); + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; + queryParams[FILED_CRED_OWNER] = "DM"; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accesser.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} + +int32_t AuthSrcConfirmState::Action(std::shared_ptr context) +{ + LOGI("start."); + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + // check version compatibility + context->timer->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + if (CompareVersion(context->accessee.dmVersion, std::string(DM_VERSION_5_1_0))) { + LOGE("incompatible version %{public}s compare to 5.1.0", + context->accessee.dmVersion.c_str()); + context->reason = ERR_DM_VERSION_INCOMPATIBLE; + return ERR_DM_VERSION_INCOMPATIBLE; + } + + context->accessee.isOnline = SoftbusCache::GetInstance().CheckIsOnline(context->accessee.deviceIdHash); + JsonObject credInfo; + GetSrcCredentialInfo(context, credInfo); + JsonObject aclInfo; + GetSrcAclInfo(context, credInfo, aclInfo); + context->accesser.aclList = aclInfo.Dump(); + JsonObject credTypeJson; + GetSrcCredType(context, credInfo, credTypeJson); + context->accesser.credTypeList = credTypeJson.Dump(); + // update credType negotiate result + JsonObject credTypeNegoResult; + NegotiateCredential(context, credTypeNegoResult); + context->accesser.credTypeList = credTypeNegoResult.Dump(); + // update acl negotiate result + JsonObject aclNegoResult; + NegotiateAcl(context, aclNegoResult); + context->accesser.aclList = aclNegoResult.Dump(); + + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); + context->timer->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); + return DM_OK; +} + +DmAuthStateType AuthSinkConfirmState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_CONFIRM_STATE; +} + +int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr context) +{ + LOGI("AuthSinkConfirmState::ShowConfigDialog start"); + + if (IsScreenLocked()) { + LOGE("AuthSinkConfirmState::ShowStartAuthDialog screen is locked."); + context->reason = ERR_DM_BIND_USER_CANCEL; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + return STOP_BIND; + } + + JsonObject jsonObj; + jsonObj[TAG_CUSTOM_DESCRIPTION] = context->customData; + jsonObj[TAG_LOCAL_DEVICE_TYPE] = context->accesser.deviceType; + jsonObj[TAG_REQUESTER] = context->accesser.deviceName; + jsonObj[TAG_USER_ID] = context->accessee.userId; // Reserved + jsonObj[TAG_HOST_PKGLABEL] = context->sessionName; + jsonObj[TOKENID] = context->accessee.tokenId; + + const std::string params = jsonObj.Dump(); + DmDialogManager::GetInstance().ShowConfirmDialog(params); + + LOGI("AuthSinkConfirmState::ShowConfigDialog end"); + return DM_OK; +} + +void AuthSinkConfirmState::NegotiateCredential(std::shared_ptr context, JsonObject &credTypeNegoResult) +{ + CHECK_NULL_VOID(context); + JsonObject accesseeCredTypeList; + accesseeCredTypeList.Parse(context->accessee.credTypeList); + JsonObject accesserCredTypeList; + accesserCredTypeList.Parse(context->accesser.credTypeList); + LOGI("yangwei accesseeCredTypeList %{public}s, accesserCredTypeList %{public}s.", + accesseeCredTypeList.Dump().c_str(), accesserCredTypeList.Dump().c_str()); + if (accesseeCredTypeList.IsDiscarded() || accesserCredTypeList.IsDiscarded()) { + LOGE("CredTypeList invalid."); + return; + } + if (accesseeCredTypeList.Contains("identicalCredType") && accesserCredTypeList.Contains("identicalCredType")) { + LOGI("have identical credential."); + credTypeNegoResult["identicalCredType"] = DM_IDENTICAL_ACCOUNT; + } + if (accesseeCredTypeList.Contains("shareCredType") && accesserCredTypeList.Contains("shareCredType")) { + LOGI("have share credential."); + credTypeNegoResult["shareCredType"] = DM_SHARE; + } + if (accesseeCredTypeList.Contains("pointTopointCredType") && accesserCredTypeList.Contains("pointTopointCredType")) { + LOGI("have point_to_point credential."); + credTypeNegoResult["pointTopointCredType"] = DM_POINT_TO_POINT; + } + if (accesseeCredTypeList.Contains("lnnCredType") && accesserCredTypeList.Contains("lnnCredType")) { + LOGI("have lnn credential."); + credTypeNegoResult["lnnCredType"] = DM_LNN; + context->accessee.isGenerateLnnCredential = false; + } + return; +} + +void AuthSinkConfirmState::NegotiateAcl(std::shared_ptr context, JsonObject &aclNegoResult) +{ + CHECK_NULL_VOID(context); + JsonObject accesseeAclList; + accesseeAclList.Parse(context->accessee.aclList); + JsonObject accesserAclList; + accesserAclList.Parse(context->accesser.aclList); + LOGI("yangwei accesseeAclList %{public}s, accesserAclList %{public}s.", + accesseeAclList.Dump().c_str(), accesserAclList.Dump().c_str()); + if (accesseeAclList.IsDiscarded() || accesserAclList.IsDiscarded()) { + LOGE("aclList invalid."); + return; + } + if (accesseeAclList.Contains("identicalAcl") && accesserAclList.Contains("identicalAcl")) { + LOGI("have identical acl."); + aclNegoResult["identicalAcl"] = DM_IDENTICAL_ACCOUNT; + context->accesser.isAuthed = true; + } + if (accesseeAclList.Contains("shareCredType") && accesserAclList.Contains("shareCredType")) { + LOGI("have share acl."); + aclNegoResult["shareAcl"] = DM_SHARE; + context->accesser.isAuthed = true; + } + if (accesseeAclList.Contains("pointTopointAcl") && accesserAclList.Contains("pointTopointAcl")) { + LOGI("have point_to_point acl."); + aclNegoResult["pointTopointAcl"] = DM_POINT_TO_POINT; + context->accesser.isAuthed = true; + } + if (accesseeAclList.Contains("lnnAcl") && accesserAclList.Contains("lnnAcl")) { + LOGI("have lnn acl."); + aclNegoResult["lnnAcl"] = DM_LNN; + context->accessee.isPutLnnAcl = false; + } +} + +void AuthSinkConfirmState::MatchFallBackCandidateList( + std::shared_ptr context, DmAuthType authType) +{ + for (size_t i = 0; i < MAX_FALLBACK_LOOPKUP_TIMES; i++) { + auto it = g_pinAuthTypeFallBackMap.find({context->accessee.bundleName, authType}); + if (it != g_pinAuthTypeFallBackMap.end()) { + authType = it->second; + context->authTypeList.push_back(authType); + } else { + break; + } + } +} + +void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr context) +{ + // query ServiceInfo by accessee.bundleName and authType from client + OHOS::DistributedDeviceProfile::LocalServiceInfo srvInfo; + auto ret = DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType( + context->accessee.bundleName, context->authType, srvInfo); + if (ret == OHOS::DistributedDeviceProfile::DP_SUCCESS) { + LOGI("AuthSinkConfirmState::ReadServiceInfo found"); + // ServiceInfo found + context->serviceInfoFound = true; + context->authBoxType = srvInfo.GetAuthBoxType(); // read authBoxType + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { + std::string pinCode = srvInfo.GetPinCode(); // read pincode + if (AuthSinkStatePinAuthComm::IsPinCodeValid(pinCode)) { + context->pinCode = std::stoi(pinCode.c_str()); + } + srvInfo.SetPinCode("******"); + DeviceProfileConnector::GetInstance().UpdateLocalServiceInfo(srvInfo); + } + if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { // no authorization box + int32_t authResult = srvInfo.GetAuthType(); // read authResult + if (authResult == 0) { + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH; + } else if (authResult == OHOS::DistributedDeviceProfile::NUM_1) { + context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + } else if (authResult == OHOS::DistributedDeviceProfile::NUM_6) { + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + } else { + context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + } + } + context->customData = srvInfo.GetDescription(); // read customData + } else if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && + AuthSinkStatePinAuthComm::IsAuthCodeReady(context)) { + // only special scenarios can import pincode + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // no authorization box + } else { + // not special scenarios, reset authResult to cancel + context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // default: tristate box + } +} + +int32_t AuthSinkConfirmState::Action(std::shared_ptr context) +{ + LOGI("start."); + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + JsonObject credTypeNegoResult; + JsonObject aclNegoResult; + NegotiateCredential(context, credTypeNegoResult); + context->accesser.credTypeList = credTypeNegoResult.Dump(); + context->accesser.aclList = aclNegoResult.Dump(); + NegotiateAcl(context, aclNegoResult); + if (credTypeNegoResult.Dump() != context->accesser.credTypeList || aclNegoResult.Dump() != context->accesser.aclList) { + LOGE("compability negotiate not match."); + context->reason = ERR_DM_CAPABILITY_NEGOTIATE_FAILED; + return ERR_DM_FAILED; + } + int32_t ret = NegotiateProcess::GetInstance().HandleNegotiateResult(context); + if (ret != DM_OK) { + LOGE("HandleNegotiateResult failed ret %{public}d.", ret); + return ret; + } + if (context->needBind) { + return ProcessBindAuthorize(context); + } else { + return ProcessNoBindAuthorize(context); + } +} + +int32_t AuthSinkConfirmState::ProcessBindAuthorize(std::shared_ptr context) +{ + LOGI("start."); + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + ReadServiceInfo(context); + context->authTypeList.clear(); + context->authTypeList.push_back(context->authType); + MatchFallBackCandidateList(context, context->authType); + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && + (context->serviceInfoFound || AuthSinkStatePinAuthComm::IsAuthCodeReady(context)) && + context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_1) { + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + if (ShowConfigDialog(context) != DM_OK) { + LOGE("ShowConfigDialog failed"); + return ERR_DM_FAILED; + } + if (DmEventType::ON_USER_OPERATION != + context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { + LOGE("AuthSinkConfirmState::Action ON_USER_OPERATION err"); + return ERR_DM_FAILED; + } + if (context->authResult == USER_OPERATION_TYPE_CANCEL_AUTH) { + LOGE("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); + context->reason = ERR_DM_BIND_USER_CANCEL; + return ERR_DM_FAILED; + } + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + context->authStateMachine->TransitionTo(std::make_shared()); + } + context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + return ERR_DM_FAILED; +} + +int32_t AuthSinkConfirmState::ProcessNoBindAuthorize(std::shared_ptr context) +{ + LOGI("start."); + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + JsonObject accesseeCredTypeList; + accesseeCredTypeList.Parse(context->accessee.credTypeList); + if (accesseeCredTypeList.IsDiscarded()) { + LOGE("CredTypeList invalid."); + return ERR_DM_FAILED; + } + if (accesseeCredTypeList.Contains("identicalCredType")) { + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->accessee.transmitCredentialId = GetCredIdByCredType(context, DM_IDENTICAL_ACCOUNT); + } else if (accesseeCredTypeList.Contains("shareCredType")) { + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->accessee.transmitCredentialId = GetCredIdByCredType(context, DM_SHARE); + } else if (accesseeCredTypeList.Contains("pointTopointCredType")) { + context->accessee.transmitCredentialId = GetCredIdByCredType(context, DM_POINT_TO_POINT); + } else { + LOGE("credTypeList invalid."); + } + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +std::string AuthSinkConfirmState::GetCredIdByCredType(std::shared_ptr context, int32_t credType) +{ + LOGI("credType %{public}d.", credType); + CHECK_NULL_RETURN(context, UNVALID_CREDTID); + if (context->accessee.credentialInfos.find(credType) != context->accessee.credentialInfos.end()) { + LOGE("invalid credType."); + return UNVALID_CREDTID; + } + std::string credInfoStr = context->accessee.credentialInfos[credType]; + LOGI("yangwei credInfoStr %{public}s.", credInfoStr.c_str()); + JsonObject credInfoJson; + credInfoJson.Parse(credInfoStr); + if (credInfoJson.IsDiscarded() || !credInfoJson.Contains(FILED_CRED_ID) || + !credInfoJson[FILED_CRED_ID].IsNumberInteger()) { + LOGE("credInfoStr invalid."); + return UNVALID_CREDTID; + } + return credInfoJson[FILED_CRED_ID].Get(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp new file mode 100644 index 000000000..301bec95d --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -0,0 +1,529 @@ +/* + * Copyright (c) 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 +#include +#include +#include +#include "dm_auth_context.h" +#include "dm_auth_manager_base.h" +#include "dm_auth_message_processor.h" +#include "dm_auth_state.h" +#include "dm_auth_state_machine.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "deviceprofile_connector.h" +#include "hichain_auth_connector.h" +#include "multiple_user_connector.h" + +namespace OHOS { +namespace DistributedHardware { + +namespace { + +// tag in Lowercase, need by hichain tag +constexpr const char* TAG_LOWER_DEVICE_ID = "deviceId"; +constexpr const char* TAG_LOWER_USER_ID = "userId"; + +constexpr const char* DM_AUTH_CREDENTIAL_OWNER = "DM"; + +// decrypt process +int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmEventType event) +{ + if (context->transmitData.empty()) { + LOGE("DmAuthMessageProcessor::CreateMessageReqCredAuthStart failed, get onTransmitData failed."); + return ERR_DM_FAILED; + } + + int32_t ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (ret != DM_OK) { + LOGE("AuthCredentialTransmitDecryptProcess: ProcessCredData transmit data failed"); + return ERR_DM_FAILED; + } + + if (context->authStateMachine->WaitExpectEvent(event) != event) { + LOGE("AuthCredentialTransmitDecryptProcess: Hichain auth transmit data failed"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t AuthCredentialTransmitSend(std::shared_ptr context, DmMessageType msgType) +{ + if (context->transmitData.empty()) { + LOGE("AuthCredentialTransmitSend: Get onTransmitData failed."); + return ERR_DM_FAILED; + } + + std::string message = + context->authMessageProcessor->CreateMessage(msgType, context); + if (message.empty()) { + LOGE("AuthCredentialTransmitSend: CreateMessage AuthCredential transmit data failed"); + return ERR_DM_FAILED; + } + + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + +void SetAuthContext(int32_t skId, int64_t &appSkTimeStamp, int32_t &appSessionKeyId) +{ + appSkTimeStamp = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + appSessionKeyId = skId; + return; +} + +} + +DmAuthStateType AuthSrcCredentialAuthNegotiateState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE; +} + +// Parse the ontransmit data, respond with 161 message +int32_t AuthSrcCredentialAuthNegotiateState::Action(std::shared_ptr context) +{ + // decrypt and transmit transmitData + int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); + if (ret != DM_OK) { + return ret; + } + + // Send 161 message + return AuthCredentialTransmitSend(context, DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE); +} + +DmAuthStateType AuthSrcCredentialAuthDoneState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE; +} + +int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr context) +{ + // decrypt and transmit transmitData + int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_SESSION_KEY_RETURNED); + if (ret != DM_OK) { + return ret; + } + + // Authentication completion triggers the Onfinish callback event. + if (context->authStateMachine->WaitExpectEvent(ON_FINISH) != ON_FINISH) { + LOGE("AuthSrcCredentialAuthDoneState::Action Hichain auth SINK transmit data failed"); + return ERR_DM_FAILED; + } + DmMessageType msgType; + int32_t skId; + ret = context->authMessageProcessor->SaveSessionKeyToDP(skId); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialAuthDoneState::Action DP save user session key failed"); + return ret; + } + + // first time joinLnn, auth lnnCredential + if (context->isOnline == false && context->isAppCredentialVerified == false) { + context->isAppCredentialVerified = true; + SetAuthContext(skId, context->accesser.transmitSkTimeStamp, context->accesser.transmitSessionKeyId); + msgType = MSG_TYPE_REQ_CREDENTIAL_AUTH_START; + ret = context->hiChainAuthConnector->AuthCredential(context->accesser.userId, context->requestId, + context->accesser.lnnCredentialId, std::string("")); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialAuthDoneState::Action Hichain auth credentail failed"); + return ret; + } + + // wait for onTransmit event + if (context->authStateMachine->WaitExpectEvent(ON_TRANSMIT) != ON_TRANSMIT) { + LOGE("AuthSrcCredentialAuthDoneState::Action failed, ON_TRANSMIT event not arrived."); + return ERR_DM_FAILED; + } + } else if (context->isOnline == false) { // First-time authentication and Lnn credential process + SetAuthContext(skId, context->accesser.lnnSkTimeStamp, context->accesser.lnnSessionKeyId); + msgType = MSG_TYPE_REQ_DATA_SYNC; + } else { // Non-first-time authentication transport credential process + SetAuthContext(skId, context->accesser.transmitSkTimeStamp, context->accesser.transmitSessionKeyId); + msgType = MSG_TYPE_REQ_DATA_SYNC; + } + std::string message = + context->authMessageProcessor->CreateMessage(msgType, context); + if (message.empty()) { + LOGE("AuthSrcCredentialAuthDoneState::Action CreateMessage failed"); + return ERR_DM_FAILED; + } + + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + +DmAuthStateType AuthSinkCredentialAuthStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE; +} + +int32_t AuthSinkCredentialAuthStartState::Action(std::shared_ptr context) +{ + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + + int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); + if (ret != DM_OK) { + return ret; + } + + return AuthCredentialTransmitSend(context, DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START); +} + +DmAuthStateType AuthSinkCredentialAuthNegotiateState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE; +} + +int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptr context) +{ + int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); + if (ret != DM_OK) { + return ret; + } + + // Construct and send 171 message + ret = AuthCredentialTransmitSend(context, DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE); + if (ret != DM_OK) { + return ret; + } + + if (context->authStateMachine->WaitExpectEvent(ON_SESSION_KEY_RETURNED) != ON_SESSION_KEY_RETURNED) { + LOGE("AuthSinkCredentialAuthNegotiateState::Action Hichain auth SINK transmit data failed"); + return ERR_DM_FAILED; + } + + if (context->authStateMachine->WaitExpectEvent(ON_FINISH) != ON_FINISH) { + LOGE("AuthSinkCredentialAuthNegotiateState::Action Hichain auth SINK transmit data failed"); + return ERR_DM_FAILED; + } + int32_t skId; + ret = context->authMessageProcessor->SaveSessionKeyToDP(skId); + if (ret != DM_OK) { + LOGE("AuthSinkCredentialAuthNegotiateState::Action DP save user session key failed"); + return ret; + } + + // First lnn cred auth, second time receiving 161 message + if (context->isOnline == false && + context->isAppCredentialVerified == true) { + context->accessee.lnnSkTimeStamp = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); + context->accessee.lnnSessionKeyId = skId; + } else { // Twice transport cred auth + context->isAppCredentialVerified = true; + context->accessee.transmitSkTimeStamp = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); + context->accessee.transmitSessionKeyId = skId; + } + return DM_OK; +} + +// Generate the json string of authParams in the credential negotiation state +std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authorizedScope, + DmAuthCredentialAddMethod method, const std::shared_ptr &authContext) +{ + LOGI("AuthCredentialAgreeState::CreateAuthParamsString start."); + + if ((authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP) || + (method != DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE && method != DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT)) { + return std::string(""); + } + + JsonObject jsonObj; + if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) { + jsonObj[TAG_METHOD] = method; + } + + jsonObj[TAG_LOWER_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? + authContext->GetDeviceId(DM_AUTH_LOCAL_SIDE) : authContext->GetDeviceId(DM_AUTH_REMOTE_SIDE); + if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { + jsonObj[TAG_PEER_USER_SPACE_ID] = std::to_string(authContext->GetUserId(DM_AUTH_REMOTE_SIDE)); + } + jsonObj[TAG_LOWER_USER_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? + authContext->GetAccountId(DM_AUTH_LOCAL_SIDE) : authContext->GetAccountId(DM_AUTH_REMOTE_SIDE); + jsonObj[TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; + jsonObj[TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; + jsonObj[TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? + DM_AUTH_KEY_FORMAT_ASYMM_GENERATE : DM_AUTH_KEY_FORMAT_ASYMM_IMPORT; + jsonObj[TAG_ALGORITHM_TYPE] = DM_AUTH_ALG_TYPE_ED25519; + jsonObj[TAG_PROOF_TYPE] = DM_AUTH_CREDENTIAL_PROOF_PSK; + if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { + jsonObj[TAG_KEY_VALUE] = authContext->GetPublicKey(DM_AUTH_REMOTE_SIDE, authorizedScope); + } + jsonObj[TAG_AUTHORIZED_SCOPE] = authorizedScope; + if (authorizedScope == DM_AUTH_SCOPE_APP) { + std::vector tokenIds = {std::to_string(authContext->accesser.tokenId), + std::to_string(authContext->accessee.tokenId)}; + jsonObj[TAG_AUTHRIZED_APP_LIST] = tokenIds; + } + jsonObj[TAG_CREDENTIAL_OWNER] = DM_AUTH_CREDENTIAL_OWNER; + + LOGI("AuthCredentialAgreeState::CreateAuthParamsString leave."); + return jsonObj.Dump(); +} + +// Generate credential ID and public key +int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authorizedScope, + std::shared_ptr &authContext) +{ + LOGI("AuthCredentialAgreeState::GenerateCredIdAndPublicKey start."); + if ((authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP) || + authContext == nullptr || authContext->hiChainAuthConnector == nullptr) { + return ERR_DM_FAILED; + } + + std::string authParamsString = CreateAuthParamsString(authorizedScope, + DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE, authContext); + if (authParamsString == "") { + LOGE("AuthCredentialAgreeState::GenerateCredIdAndPublicKey() error, create authParamsString failed."); + return ERR_DM_FAILED; + } + + int32_t osAccountId = (authContext->direction == DM_AUTH_SOURCE) ? + authContext->accesser.userId : authContext->accessee.userId; + std::string credId; + int32_t ret = authContext->hiChainAuthConnector->AddCredential(osAccountId, authParamsString, credId); + if (ret != DM_OK) { + LOGE("AuthCredentialAgreeState::GenerateCredIdAndPublicKey() error, add credential failed."); + return ret; + } + + std::string publicKey; + ret = authContext->hiChainAuthConnector->ExportCredential(osAccountId, credId, publicKey); + if (ret != DM_OK) { + LOGE("AuthCredentialAgreeState::GenerateCredIdAndPublicKey(), export publicKey failed."); + authContext->hiChainAuthConnector->DeleteCredential(osAccountId, credId); + return ret; + } + + (void)authContext->SetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope, credId); + (void)authContext->SetPublicKey(DM_AUTH_LOCAL_SIDE, authorizedScope, publicKey); + LOGI("AuthCredentialAgreeState::GenerateCredIdAndPublicKey credId=%{public}s, publicKey=%{public}s.\n", + authContext->GetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope).c_str(), + authContext->GetPublicKey(DM_AUTH_LOCAL_SIDE, authorizedScope).c_str()); + LOGI("AuthCredentialAgreeState::GenerateCredIdAndPublicKey leave."); + return DM_OK; +} + +// Get the negotiation credential ID by agree credential +int32_t AuthCredentialAgreeState::AgreeCredential(DmAuthScope authorizedScope, + std::shared_ptr &authContext) +{ + LOGI("AuthCredentialAgreeState::AgreeCredential start."); + if ((authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP) || authContext == nullptr) { + return ERR_DM_FAILED; + } + + std::string authParamsString = CreateAuthParamsString(authorizedScope, + DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, authContext); + if (authParamsString == "") { + LOGE("AuthCredentialAgreeState::AgreeCredential error, create authParamsString failed."); + return ERR_DM_FAILED; + } + + int32_t osAccountId = authContext->direction == DM_AUTH_SOURCE ? + authContext->accesser.userId : authContext->accessee.userId; + std::string selfCredId = authContext->GetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope); + std::string credId; + LOGI("AuthCredentialAgreeState::AgreeCredential agree with accountId %{public}d and param %{public}s.", + osAccountId, authParamsString.c_str()); + int32_t ret = authContext->hiChainAuthConnector->AgreeCredential(osAccountId, selfCredId, + authParamsString, credId); + if (ret != DM_OK) { + LOGE("AuthCredentialAgreeState::AgreeCredential error, agree credential failed."); + } + + (void)authContext->SetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope, credId); + LOGI("AuthCredentialAgreeState::AgreeCredential leave."); + return DM_OK; +} + +DmAuthStateType AuthSrcCredentialExchangeState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE; +} + +int32_t AuthSrcCredentialExchangeState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcCredentialExchangeState::Action() start."); + int32_t ret = ERR_DM_FAILED; + context->isAppCredentialVerified = false; + + if (!NeedAgreeAcl(context)) { + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + + if (!NeedAgreeCredential(context)) { + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + + // First authentication, generate LNN credentials and public key + if (!context->isOnline) { + ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_USER, context); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialExchangeState::Action() error, generate user credId and publicKey failed."); + return ret; + } + } + + // Generate transmit credentials and public key + ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_APP, context); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialExchangeState::Action() error, generate app credId and publicKey failed."); + return ret; + } + + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, context); + LOGI("AuthSrcCredentialExchangeState::Action() leave."); + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + +DmAuthStateType AuthSinkCredentialExchangeState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE; +} + +int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkCredentialExchangeState::Action start."); + int32_t ret = ERR_DM_FAILED; + std::string tmpCredId; + int32_t osAccountId = context->accessee.userId; + context->isAppCredentialVerified = false; + + if (context == nullptr || context->hiChainAuthConnector == nullptr || + context->authMessageProcessor == nullptr || context->softbusConnector == nullptr) { + return ret; + } + + // First authentication lnn cred + if (!context->isOnline) { + // Generate credentials and public key + ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_USER, context); + if (ret != DM_OK) { + LOGE("AuthSinkCredentialExchangeState::Action failed, generate user cred and publicKey failed."); + return ret; + } + + // Agree credentials + tmpCredId = context->accessee.lnnCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_USER, context); + if (ret != DM_OK) { + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_USER, ""); + LOGE("AuthSinkCredentialExchangeState::Action failed, agree user cred failed."); + return ret; + } + + // Delete temporary credentials + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + } + + // Generate transport credentials and public key + ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_APP, context); + if (ret != DM_OK) { + LOGE("AuthSinkCredentialExchangeState::Action failed, generate app cred and publicKey failed."); + return ret; + } + + // Agree transport credentials and public key + tmpCredId = context->accessee.transmitCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_APP, context); + if (ret != DM_OK) { + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_APP, ""); + LOGE("AuthSinkCredentialExchangeState::Action failed, agree app cred failed."); + return ret; + } + + // Delete temporary transport credentials + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, context); + LOGI("AuthSinkCredentialExchangeState::Action leave."); + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + +DmAuthStateType AuthSrcCredentialAuthStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE; +} + +int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr context) +{ + LOGI(" AuthSrcCredentialAuthStartState::Action start."); + int32_t ret = ERR_DM_FAILED; + std::string tmpCredId; + int32_t osAccountId = context->accesser.userId; + + if (context == nullptr || context->hiChainAuthConnector == nullptr || + context->authMessageProcessor == nullptr || context->softbusConnector == nullptr) { + return ret; + } + + if (NeedAgreeCredential(context)) { + // First authentication + if (!context->isOnline) { + // Agree lnn credentials and public key + tmpCredId = context->accesser.lnnCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_USER, context); + if (ret != DM_OK) { + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_USER, ""); + LOGE("AuthSrcCredentialAuthStartState::Action failed, agree user cred failed."); + return ret; + } + + // Delete temporary lnn credentials + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + } + + // Agree transport credentials and public key + tmpCredId = context->accesser.transmitCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_APP, context); + if (ret != DM_OK) { + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_APP, ""); + LOGE("AuthSrcCredentialAuthStartState::Action failed, agree app cred failed."); + return ret; + } + + // Delete temporary transport credentials + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + } + + // Transport credential authentication + ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, + context->accesser.transmitCredentialId, std::string("")); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialAuthStartState::Action failed, auth app cred failed."); + return ret; + } + + if (context->authStateMachine->WaitExpectEvent(ON_TRANSMIT) != ON_TRANSMIT) { + LOGE("AuthSrcCredentialAuthStartState::Action failed, ON_TRANSMIT event not arrived."); + return ERR_DM_FAILED; + } + + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_CREDENTIAL_AUTH_START, context); + LOGI(" AuthSrcCredentialAuthStartState::Action leave."); + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp new file mode 100644 index 000000000..12db712f6 --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -0,0 +1,542 @@ +/* + * Copyright (c) 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 +#include + +#include "accesstoken_kit.h" +#include "access_control_profile.h" +#include "accesser.h" +#include "accessee.h" +#include "auth_manager.h" +#include "app_manager.h" +#include "dm_crypto.h" +#include "dm_log.h" +#include "dm_timer.h" +#include "dm_radar_helper.h" +#include "dm_language_manager.h" +#include "dm_constants.h" +#include "dm_anonymous.h" +#include "dm_random.h" +#include "dm_auth_context.h" +#include "dm_auth_state.h" +#include "deviceprofile_connector.h" +#include "distributed_device_profile_errors.h" +#include "device_auth.h" +#include "hap_token_info.h" +#include "json_object.h" +#include "multiple_user_connector.h" +#include "os_account_manager.h" +#include "parameter.h" + +using namespace OHOS::Security::AccessToken; + +namespace OHOS { +namespace DistributedHardware { +const std::string SYSTEM_LANGUAGE_KEY = "persist.global.language"; + +#ifdef DEVICE_MANAGER_COMMON_FLAG +constexpr int32_t PROCESS_NAME_WHITE_LIST_NUM = 1; +constexpr const static char* PROCESS_NAME_WHITE_LIST[PROCESS_NAME_WHITE_LIST_NUM] = { + "com.example.myapplication", +}; +#endif + +DmAuthStateType AuthSrcStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_START_STATE; +} + +int32_t AuthSrcStartState::Action(std::shared_ptr context) +{ + return DM_OK; +} + +DmAuthStateType AuthSrcNegotiateStateMachine::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE; +} + +int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr context) +{ + LOGI("AuthSrcNegotiateStateMachine::Action sessionId %{public}d.", context->sessionId); + + context->reply = ERR_DM_AUTH_REJECT; + context->accessee.dmVersion = ""; + + // Calculate the hash value + context->accesser.deviceIdHash = Crypto::Sha256(context->accesser.deviceId); + context->accesser.userIdHash = Crypto::Sha256(std::to_string(context->accesser.userId)); + context->accesser.accountIdHash = Crypto::Sha256(context->accesser.accountId); + context->accesser.tokenIdHash = Crypto::Sha256(std::to_string(context->accesser.tokenId)); + + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_ACL_NEGOTIATE, context); + context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); + if (context->timer != nullptr) { + context->timer->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), + [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); + }); + } + + return DM_OK; +} + +DmAuthStateType AuthSinkNegotiateStateMachine::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE; +} + +#ifdef DEVICE_MANAGER_COMMON_FLAG +bool CheckProcessNameInWhiteList(const std::string &processName) +{ + LOGI("DmAuthManager::CheckProcessNameInWhiteList start"); + if (processName.empty()) { + LOGE("processName is empty"); + return false; + } + uint16_t index = 0; + for (; index < PROCESS_NAME_WHITE_LIST_NUM; ++index) { + std::string whitePkgName(PROCESS_NAME_WHITE_LIST[index]); + if (processName == whitePkgName) { + LOGI("processName = %{public}s in whiteList.", processName.c_str()); + return true; + } + } + LOGI("CheckProcessNameInWhiteList: %{public}s invalid.", processName.c_str()); + return false; +} +#endif + +int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + // 1. Get deviceId + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + context->accessee.deviceId = std::string(localDeviceId); + context->accessee.deviceIdHash = Crypto::Sha256(context->accessee.deviceId); + + // 2. Get userId + context->accessee.userId = MultipleUserConnector::GetUserIdByDisplayId( + static_cast(context->accessee.displayId)); + if (context->accessee.userId < 0) { + LOGE("get userId failed."); + return ERR_DM_GET_LOCAL_USERID_FAILED; + } + context->accessee.userIdHash = Crypto::Sha256(std::to_string(context->accessee.userId)); + + // 3. Get accountId + context->accessee.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context->accessee.userId); + context->accessee.accountIdHash = Crypto::Sha256(context->accessee.accountId); + + // 4. Get tokenId + if (AppManager::GetInstance().GetNativeTokenIdByName(context->accessee.bundleName, + context->accessee.tokenId) == DM_OK) { + context->accessee.bindLevel = DmRole::DM_ROLE_SA; + } else if (AppManager::GetInstance().GetHapTokenIdByName(context->accessee.userId, context->accessee.bundleName, 0, + context->accessee.tokenId) == DM_OK) { + context->accessee.bindLevel = DmRole::DM_ROLE_FA; + } else { + LOGE("sink not contain the bundlename %{public}s.", context->accessee.bundleName.c_str()); + context->reason = ERR_DM_NOT_SYSTEM_APP; + context->reply = ERR_DM_NOT_SYSTEM_APP; + return ERR_DM_NOT_SYSTEM_APP; + } +#ifdef DEVICE_MANAGER_COMMON_FLAG + if (CheckProcessNameInWhiteList(context->accessee.bundleName)) { + context->accessee.bindLevel = DmRole::DM_ROLE_USER; + } +#endif + context->accessee.tokenIdHash = Crypto::Sha256(std::to_string(context->accessee.tokenId)); + context->accesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceIdHash, true); + context->accesser.language = DmLanguageManager::GetInstance().GetSystemParam(SYSTEM_LANGUAGE_KEY); + context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); + context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); + return DM_OK; +} + +int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + int32_t ret = RespQueryAcceseeIds(context); + if (ret != DM_OK) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get all id."); + return ERR_DM_FAILED; + } + JsonObject credInfo; + GetSinkCredentialInfo(context, credInfo); + JsonObject aclInfo; + GetSinkAclInfo(context, credInfo, aclInfo); + context->accessee.aclList = aclInfo.Dump(); + JsonObject credTypeJson; + GetSinkCredType(context, credInfo, credTypeJson); + context->accessee.credTypeList = credTypeJson.Dump(); + return DM_OK; +} + +int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr context) +{ + LOGI("AuthSinkNegotiateStateMachine::Action sessionid %{public}d", context->sessionId); + + // 1. Create an authorization timer + if (context->timer != nullptr) { + context->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + AUTHENTICATE_TIMEOUT, + [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); + }); + } + + // To be compatible with historical versions, use ConvertSrcVersion to get the actual version on the source side. + std::string preVersion = std::string(DM_VERSION_5_0_OLD_MAX); + LOGI("AuthSinkNegotiateStateMachine::Action start version compare %{public}s to %{public}s", + context->accesser.dmVersion.c_str(), preVersion.c_str()); + if (CompareVersion(context->accesser.dmVersion, preVersion) == false) { + LOGE("AuthSinkNegotiateStateMachine::Action incompatible version"); + context->reason = ERR_DM_VERSION_INCOMPATIBLE; + return ERR_DM_VERSION_INCOMPATIBLE; + } + + int32_t ret = ProcRespNegotiate5_1_0(context); + if (ret != DM_OK) { + LOGE("AuthSinkNegotiateStateMachine::Action proc response negotiate failed"); + return ret; + } + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_ACL_NEGOTIATE, context); + context->timer->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), + [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); + }); + return DM_OK; +} + +void AuthSinkNegotiateStateMachine::GetSinkCredType(std::shared_ptr context, + JsonObject &credInfo, JsonObject &credTypeJson) +{ + CHECK_NULL_VOID(context); + std::vector deleteCredInfo; + for (const auto &item : credInfo.Items()) { + LOGI("yangwei credInfo %{public}s.", item.Dump().c_str()); + std::string key = item.Key(); + if (!item.Contains(key) || !item[key].IsObject() || !item[key].Contains(TAG_CRED_TYPE) || + !item[key][TAG_CRED_TYPE].IsNumberInteger()) { + deleteCredInfo.push_back(key); + continue; + } + int32_t credType = item[key][TAG_CRED_TYPE].Get(); + LOGI("credType %{public}d.", credType); + if (credType == DM_IDENTICAL_ACCOUNT) { + credTypeJson["identicalCredType"] = credType; + } else if (credType == DM_SHARE) { + credTypeJson["shareCredType"] = credType; + } else if (credType == DM_POINT_TO_POINT) { + credTypeJson["pointTopointCredType"] = credType; + } else if (credType == DM_LNN) { + credTypeJson["lnnCredType"] = credType; + } else { + continue; + } + context->accessee.credentialInfos[credType] = item.Dump(); + } + for (const auto &item : deleteCredInfo) { + credInfo.Erase(item); + } +} + +void AuthSinkNegotiateStateMachine::GetSinkAclInfo(std::shared_ptr context, + JsonObject &credInfo, JsonObject &aclInfo) +{ + CHECK_NULL_VOID(context); + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + for (const auto &item : profiles) { + std::string trustDeviceId = item.GetTrustDeviceId(); + std::string trustDeviceIdHash = Crypto::Sha256(trustDeviceId); + if (trustDeviceIdHash != context->accesser.deviceIdHash) { + LOGE("Acl trust deviceId %{public}s hash %{public}s, not equal accesser deviceId %{public}s.", + GetAnonyString(trustDeviceId).c_str(), GetAnonyString(trustDeviceIdHash).c_str(), + GetAnonyString(context->accesser.deviceIdHash).c_str()); + continue; + } + uint32_t bindType = item.GetBindType(); + switch (bindType) { + case DM_IDENTICAL_ACCOUNT: + if (IdenticalAccountAclCompare(context, item.GetAccesser(), item.GetAccessee())) { + aclInfo["identicalAcl"] = DM_IDENTICAL_ACCOUNT; + context->accessee.aclProfiles[DM_IDENTICAL_ACCOUNT] = item; + break; + } + case DM_SHARE: + if (ShareAclCompare(context, item.GetAccesser(), item.GetAccessee()) && + CheckCredIdInAcl(item, credInfo, bindType)) { + aclInfo["shareAcl"] = bindType; + context->accessee.aclProfiles[DM_SHARE] = item; + break; + } + case DM_POINT_TO_POINT: + // application + if (Point2PointAclCompare(context, item.GetAccesser(), item.GetAccessee()) && + CheckCredIdInAcl(item, credInfo, bindType)) { + aclInfo["pointTopointAcl"] = bindType; + context->accessee.aclProfiles[DM_POINT_TO_POINT] = item; + break; + } + // lnn + if (LnnAclCompare(context, item.GetAccesser(), item.GetAccessee()) && + CheckCredIdInAcl(item, credInfo, DM_LNN) && item.GetBindLevel() == USER) { + aclInfo["lnnAcl"] = DM_LNN; + context->accessee.aclProfiles[DM_LNN] = item; + break; + } + default: + LOGE("invalid bindType %{public}d.", bindType); + break; + } + } +} + +bool AuthSinkNegotiateStateMachine::CheckCredIdInAcl(const DistributedDeviceProfile::AccessControlProfile &profile, + JsonObject &credInfo, uint32_t bindType) +{ + std::string credId = std::to_string(profile.GetAccessee().GetAccesseeCredentialId()); + if (!credInfo.Contains(credId)) { + LOGE("credInfoJson not contain credId %{public}s.", credId.c_str()); + DeviceProfileConnector::GetInstance().DeleteAccessControlById(profile.GetAccessControlId()); + return false; + } + if (credInfo.Contains(credId) && (!credInfo[credId].IsObject() || !credInfo[credId].Contains(FILED_CRED_TYPE) || + !credInfo[credId][FILED_CRED_TYPE].IsNumberInteger())) { + LOGE("credId %{public}s contain credInfoJson invalid.", credId.c_str()); + credInfo.Erase(credId); + DeviceProfileConnector::GetInstance().DeleteAccessControlById(profile.GetAccessControlId()); + return false; + } + bool checkResult = false; + switch (bindType) { + LOGI("bindType %{public}d.", bindType); + case DM_IDENTICAL_ACCOUNT: + case DM_SHARE: + case DM_LNN: + if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { + checkResult = true; + } + break; + case DM_POINT_TO_POINT: + if (credInfo[credId][FILED_CRED_TYPE].Get() == bindType) { + std::vector appList; + credInfo[credId][FILED_AUTHORIZED_APP_LIST].Get(appList); + if (std::to_string(profile.GetAccesser().GetAccesserTokenId()) == appList[0] && + std::to_string(profile.GetAccessee().GetAccesseeTokenId()) == appList[1]) { + checkResult = true; + } else { + DeviceProfileConnector::GetInstance().DeleteAccessControlById(profile.GetAccessControlId()); + } + } + break; + default: + break; + } + return checkResult; +} + +bool AuthSinkNegotiateStateMachine::IdenticalAccountAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + // 同账号ACL需要写两条,否则会影响老化 + return accesser.GetAccesserDeviceId() == context->accessee.deviceId && + accesser.GetAccesserUserId() == context->accessee.userId && + Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accesser.deviceIdHash && + Crypto::Sha256(std::to_string(accessee.GetAccesseeUserId())) == context->accesser.userIdHash; +} + +bool AuthSinkNegotiateStateMachine::ShareAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + return accessee.GetAccesseeDeviceId() == context->accessee.deviceId && + accessee.GetAccesseeUserId() == context->accessee.userId && + Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && + Crypto::Sha256(std::to_string(accesser.GetAccesserUserId())) == context->accesser.userIdHash; +} + +bool AuthSinkNegotiateStateMachine::Point2PointAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + return accessee.GetAccesseeDeviceId() == context->accessee.deviceId && + accessee.GetAccesseeUserId() == context->accessee.userId && + accessee.GetAccesseeAccountId() == context->accessee.accountId && + accessee.GetAccesseeTokenId() == context->accessee.tokenId && + Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && + Crypto::Sha256(std::to_string(accesser.GetAccesserUserId())) == context->accesser.userIdHash && + Crypto::Sha256(accesser.GetAccesserAccountId()) == context->accesser.accountIdHash && + Crypto::Sha256(std::to_string(accesser.GetAccesserTokenId())) == context->accesser.tokenIdHash; +} + +bool AuthSinkNegotiateStateMachine::LnnAclCompare(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + // 需要增加bindType = p2p判断 + return accessee.GetAccesseeDeviceId() == context->accessee.deviceId && + accessee.GetAccesseeUserId() == context->accessee.userId && + accessee.GetAccesseeAccountId() == context->accessee.accountId && + accessee.GetAccesseeTokenId() == 0 && accessee.GetAccesseeBundleName() == "" && + Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && + Crypto::Sha256(std::to_string(accesser.GetAccesserUserId())) == context->accesser.userIdHash && + Crypto::Sha256(accesser.GetAccesserAccountId()) == context->accesser.accountIdHash && + accesser.GetAccesserTokenId() == 0 && accesser.GetAccesserBundleName() == ""; +} + +void AuthSinkNegotiateStateMachine::GetSinkCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + // get identical credential + if (context->accesser.accountIdHash == context->accessee.accountIdHash) { + GetIdenticalCredentialInfo(context, credInfo); + } + // get share credential + if (context->accesser.accountIdHash != context->accessee.accountIdHash && + context->accesser.accountIdHash != "ohosAnonymousUid" && + context->accessee.accountIdHash != "ohosAnonymousUid") { + GetShareCredentialInfo(context, credInfo); + GetP2PCredentialInfo(context, credInfo); + } + // get point_to_point credential + if (context->accesser.accountIdHash == "ohosAnonymousUid" || + context->accessee.accountIdHash == "ohosAnonymousUid") { + GetP2PCredentialInfo(context, credInfo); + } + std::vector deleteCredInfo; + for (auto& item : credInfo.Items()) { // id1:json1, id2:json2, id3:json3 + LOGI("yangwei pre credInfo %{public}s.", item.Dump().c_str()); + std::string key = item.Key(); + if (!item.Contains(key) || !item[key].IsObject()) { + LOGE("credInfo %{public}s invalid.", item.Dump().c_str()); + deleteCredInfo.push_back(key); + continue; + } + JsonItemObject credInfoTemp = item[key]; + uint32_t credType = GetCredentialType(context, credInfoTemp); + if (credType == DM_INVALIED_BINDTYPE || !credInfoTemp.Contains(FILED_CRED_TYPE) || + !credInfoTemp[FILED_CRED_TYPE].IsNumberInteger()) { + deleteCredInfo.push_back(key); + continue; + } + item[key][FILED_CRED_TYPE] = credType; + LOGI("yangwei after credInfo %{public}s.", item.Dump().c_str()); + } + for (const auto &item : deleteCredInfo) { + credInfo.Erase(item); + } +} + +void AuthSinkNegotiateStateMachine::GetIdenticalCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID] = context->accessee.deviceId; + queryParams[FILED_USER_ID] = context->accessee.accountId; + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_RELATED; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} + +void AuthSinkNegotiateStateMachine::GetShareCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID_HASH] = context->accesser.deviceIdHash; + queryParams[FILED_PEER_USER_SPACE_ID] = std::to_string(context->accesser.userId); + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} + +void AuthSinkNegotiateStateMachine::GetP2PCredentialInfo(std::shared_ptr context, + JsonObject &credInfo) +{ + CHECK_NULL_VOID(context); + JsonObject queryParams; + queryParams[FILED_DEVICE_ID_HASH] = context->accesser.deviceIdHash; + queryParams[FILED_PEER_USER_SPACE_ID] = std::to_string(context->accesser.userId); + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; + queryParams[FILED_CRED_OWNER] = "DM"; + CHECK_NULL_VOID(context->hiChainAuthConnector); + if (context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, credInfo) != DM_OK) { + LOGE("QueryCredentialInfo failed credInfo %{public}s.", credInfo.Dump().c_str()); + } +} + +uint32_t AuthSinkNegotiateStateMachine::GetCredentialType(std::shared_ptr context, + const JsonItemObject &credInfo) +{ + CHECK_NULL_RETURN(context, DM_INVALIED_BINDTYPE); + if (!credInfo.Contains(FILED_CRED_TYPE) || !credInfo[FILED_CRED_TYPE].IsNumberInteger() || + !credInfo.Contains(FILED_AUTHORIZED_SCOPE) || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumberInteger() || + !credInfo.Contains(FILED_SUBJECT) || !credInfo[FILED_SUBJECT].IsNumberInteger()) { + LOGE("credType or authorizedScope invalid."); + return DM_INVALIED_BINDTYPE; + } + int32_t credType = credInfo[FILED_CRED_TYPE].Get(); + int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); + int32_t subject = credInfo[FILED_SUBJECT].Get(); + std::vector appList; + credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); + if (credType == ACCOUNT_RELATED && authorizedScope == SCOPE_USER) { + return DM_IDENTICAL_ACCOUNT; + } + if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && + context->direction == DM_AUTH_SOURCE && subject == SUBJECT_PRIMARY) { + return DM_SHARE; + } + if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && + context->direction == DM_AUTH_SINK && subject == SUBJECT_SECONDARY) { + return DM_SHARE; + } + if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { + return DM_POINT_TO_POINT; + } + if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_USER && appList.empty()) { + return DM_LNN; + } + return DM_INVALIED_BINDTYPE; +} + +bool AuthSinkNegotiateStateMachine::HaveSameTokenId(std::shared_ptr context, + const std::vector &tokenList) +{ + // Store the token of src and sink. The size must be 2. + if (tokenList.size() != 2) { + LOGE("HaveSameTokenId invalid tokenList size."); + return false; + } + + // tokenIdList = [srcTokenId, sinkTokenId] + std::string srcTokenIdHash = Crypto::Sha256(tokenList[0]); + std::string sinkTokenIdHash = Crypto::Sha256(tokenList[1]); + + return (srcTokenIdHash == context->accesser.tokenIdHash) && + (sinkTokenIdHash == context->accessee.tokenIdHash); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp new file mode 100644 index 000000000..cfbbb4036 --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -0,0 +1,607 @@ +/* + * Copyright (c) 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 "auth_manager.h" +#include "deviceprofile_connector.h" +#include "dm_anonymous.h" +#include "dm_auth_context.h" +#include "dm_auth_message_processor.h" +#include "dm_auth_state_machine.h" +#include "dm_auth_state.h" +#include "dm_auth_state_machine.h" +#include "dm_dialog_manager.h" +#include "dm_log.h" +#include "dm_negotiate_process.h" +#include "dm_random.h" +#include "hichain_auth_connector.h" +#include "multiple_user_connector.h" +#include "service_info_profile.h" + +namespace OHOS { +namespace DistributedHardware { + +constexpr int32_t MAX_AUTH_INPUT_PIN_FAIL_TIMES = 3; +constexpr int32_t MIN_PIN_CODE = 100000; +constexpr int32_t MAX_PIN_CODE = 999999; +constexpr const char* UNVALID_CREDTID = "invalidCredId"; + +int32_t AuthSinkStatePinAuthComm::ShowAuthInfoDialog(std::shared_ptr context) +{ + LOGI("AuthSinkConfirmState::ShowAuthInfoDialog start"); + if (DmAuthState::IsScreenLocked()) { + LOGE("AuthSinkConfirmState::ShowAuthInfoDialog screen is locked."); + context->reason = ERR_DM_BIND_USER_CANCEL; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + return STOP_BIND; + } + + JsonObject jsonObj; + jsonObj[PIN_CODE_KEY] = context->pinCode; + jsonObj[TOKENID] = context->accessee.tokenId; + const std::string params = jsonObj.Dump(); + + DmDialogManager::GetInstance().ShowPinDialog(params); + + context->timer->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), + [context] (std::string name) { + AuthSinkStatePinAuthComm::HandleSessionHeartbeat(context, name); + }); + return DM_OK; +} + +void AuthSinkStatePinAuthComm::HandleSessionHeartbeat(std::shared_ptr context, std::string name) +{ + context->timer->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); + if (context->isFinished) { + return; + } + + LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); + JsonObject jsonObj; + jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT; + std::string message = jsonObj.Dump(); + context->softbusConnector->GetSoftbusSession()->SendHeartbeatData(context->sessionId, message); + + context->timer->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), + [context] (std::string name) { + AuthSinkStatePinAuthComm::HandleSessionHeartbeat(context, name); + }); + + LOGI("DmAuthManager::HandleSessionHeartbeat complete."); +} + +bool AuthSinkStatePinAuthComm::IsPinCodeValid(int32_t numpin) +{ + if (numpin < MIN_PIN_CODE || numpin > MAX_PIN_CODE) { + return false; + } + return true; +} + +bool AuthSinkStatePinAuthComm::IsPinCodeValid(const std::string& strpin) +{ + if (strpin.empty()) { + return false; + } + for (size_t i = 0; i < strpin.length(); i++) { + if (!isdigit(strpin[i])) { + return false; + } + } + int32_t pinnum = std::atoi(strpin.c_str()); + return IsPinCodeValid(pinnum); +} + +bool AuthSinkStatePinAuthComm::IsAuthCodeReady(std::shared_ptr context) +{ + if (context->importAuthCode.empty() || context->importSessionName.empty()) { + LOGE("AuthSinkStatePinAuthComm::IsAuthCodeReady, auth code not ready with authCode %{public}s and " + "sessionName %{public}s.", context->importAuthCode.c_str(), context->importSessionName.c_str()); + return false; + } + if (context->sessionName != context->importSessionName) { + LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady sessionName %{public}s not supported with " + "import sessionName %{public}s.", context->sessionName.c_str(), context->importSessionName.c_str()); + return false; + } + return true; +} + +void AuthSinkStatePinAuthComm::GeneratePincode(std::shared_ptr context) +{ + context->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); +} + +DmAuthStateType AuthSrcPinAuthStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE; +} + +int32_t AuthSrcPinAuthStartState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcPinAuthStartState::Action start"); + // auth pincode + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(osAccountId, context->requestId, + context->pinCode); + if (ret != DM_OK) { + LOGE("AuthSrcPinAuthStartState::AuthDevice call AuthCredentialPinCode failed."); + return ret; + } + // wait for onTransmit from hiChain + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // send 120 msg + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_PIN_AUTH_START, context); + return DM_OK; + } else if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSrcPinAuthStartState::AuthDevice ON_ERROR failed, maybe retry."); + return DM_OK; + } + + return STOP_BIND; +} + +DmAuthStateType AuthSinkPinAuthStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE; +} + +int32_t AuthSinkPinAuthStartState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkPinAuthStartState::Action start"); + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + if (!context->pinNegotiateStarted) { + context->pinNegotiateStarted = true; + context->timer->StartTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_PIN_AUTH_TIMEOUT_TASK, PIN_AUTH_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); + } + + // Stop the abnormal authentication process + if (context->authTypeList.empty() || + (context->authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH && + context->authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS)) { + LOGE("AuthSinkPinAuthStartState::Action invalid parameter."); + return ERR_DM_INPUT_PARA_INVALID; + } + + // process pincode auth + auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (ret != DM_OK) { + LOGE("AuthSinkPinAuthStartState::Action call ProcessCredData err."); + return ret; + } + // wait for onTransmit from hiChain + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // send 130 msg + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_PIN_AUTH_START, context); + return DM_OK; + } + if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSrcPinAuthStartState::AuthDevice ON_ERROR failed, maybe retry."); + return DM_OK; + } + return STOP_BIND; +} + +DmAuthStateType AuthSrcPinAuthMsgNegotiateState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE; +} + +int32_t AuthSrcPinAuthMsgNegotiateState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcPinAuthMsgNegotiateState::Action start"); + auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (ret != DM_OK) { + LOGE("AuthSrcPinAuthMsgNegotiateState::Action call ProcessCredData err."); + return ret; + } + // wait for onTransmit from hiChain + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // send 121 msg + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, context); + return DM_OK; + } + if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSrcPinAuthMsgNegotiateState::AuthDevice ON_ERROR failed, maybe retry."); + return DM_OK; + } + LOGE("AuthSrcPinAuthMsgNegotiateState::Action failed."); + return STOP_BIND; +} + +DmAuthStateType AuthSinkPinAuthMsgNegotiateState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE; +} + +int32_t AuthSinkPinAuthMsgNegotiateState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkPinAuthMsgNegotiateState::Action start"); + auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (ret != DM_OK) { + LOGE("AuthSinkPinAuthMsgNegotiateState::Action call ProcessCredData err."); + return ret; + } + // wait for onTransmit from hiChain + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // send 131 msg + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, context); + } else if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSinkPinAuthMsgNegotiateState::AuthDevice WAIT ON_TRANSMIT ON_ERROR failed, maybe retry."); + return DM_OK; + } else { + return STOP_BIND; + } + + retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_SESSION_KEY_RETURNED); + if (retEvent == DmEventType::ON_SESSION_KEY_RETURNED) { + retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_FINISH); + if (retEvent == DmEventType::ON_FINISH || retEvent == DmEventType::ON_ERROR) { + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + } else if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSinkPinAuthMsgNegotiateState::AuthDevice WAIT ON_SESSION_KEY_RETURNED ON_ERROR failed, maybe retry."); + return DM_OK; + } + + LOGE("AuthSinkPinAuthMsgNegotiateState::AuthDevice failed."); + return STOP_BIND; +} + +DmAuthStateType AuthSinkPinAuthDoneState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE; +} + +int32_t AuthSinkPinAuthDoneState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkPinAuthDoneState Action"); + return DM_OK; +} + +DmAuthStateType AuthSrcPinAuthDoneState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE; +} + +int32_t AuthSrcPinAuthDoneState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcPinAuthDoneState::Action start"); + std::string onTransmitData = context->transmitData; + if (context->hiChainAuthConnector->ProcessCredData(context->requestId, onTransmitData) != DM_OK) { + LOGE("AuthSrcPinAuthDoneState::Action failed, processCredData failed."); + return ERR_DM_FAILED; + } + + // wait for ON_SESSION_KEY_RETURNED from hichain + DmEventType ret = context->authStateMachine->WaitExpectEvent(ON_SESSION_KEY_RETURNED); + if (ret != ON_SESSION_KEY_RETURNED) { + if (ret == ON_ERROR) { + LOGE("AuthSrcPinAuthDoneState::Action, ON_SESSION_KEY_RETURNED event not arriverd, maybe retry."); + return DM_OK; + } else { + LOGE("AuthSrcPinAuthDoneState::Action failed, ON_SESSION_KEY_RETURNED event failed, other event arriverd."); + return ERR_DM_FAILED; + } + } + + // wait for ON_FINISH from hichain + ret = context->authStateMachine->WaitExpectEvent(ON_FINISH); + if (ret == ON_FINISH) { + LOGI("AuthSrcPinAuthDoneState::Action wait ON_FINISH done"); + return DM_OK; + } else if (ret == ON_ERROR) { + return DM_OK; + LOGE("AuthSrcPinAuthDoneState::Action, ON_FINISH event not arriverd, maybe retry."); + } + + return ERR_DM_FAILED; +} + +DmAuthStateType AuthSrcPinNegotiateStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE; +} + +int32_t AuthSrcPinNegotiateStartState::NegotiatePinAuth(std::shared_ptr context, bool firstTime) +{ + if (firstTime) { + if (context->authTypeList.empty()) { + LOGE("AuthSrcPinNegotiateStartState::Action authTypeList empty"); + context->reason = ERR_DM_AUTH_REJECT; + return ERR_DM_AUTH_REJECT; + } + context->currentAuthTypeIdx = 0; + context->authType = context->authTypeList[0]; + } else { + if (context->authType == DmAuthType::AUTH_TYPE_PIN && + context->inputPinAuthFailTimes < MAX_AUTH_INPUT_PIN_FAIL_TIMES) { + LOGI("AuthSrcPinNegotiateStartState::Action input pin auth err, retry"); + } else { + // try to fallback to next auth type + if (context->currentAuthTypeIdx + 1 >= context->authTypeList.size()) { + LOGE("AuthSrcPinNegotiateStartState::Action all auth type failed"); + context->reason = ERR_DM_AUTH_REJECT; + return ERR_DM_AUTH_REJECT; + } + context->currentAuthTypeIdx++; + context->authType = context->authTypeList[context->currentAuthTypeIdx]; + } + } + + // restart pin auth timer + context->timer->DeleteTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK)); + context->timer->StartTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_PIN_AUTH_TIMEOUT_TASK, PIN_AUTH_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { + if (AuthSinkStatePinAuthComm::IsAuthCodeReady(context)) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGE("AuthSrcPinNegotiateStartState::Action auth code not ready"); + context->reason = ERR_DM_INPUT_PARA_INVALID; + return ERR_DM_FAILED; + } + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGE("AuthSrcPinNegotiateStartState::Action authType not support"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + int32_t ret = NegotiateProcess::GetInstance().HandleNegotiateResult(context); + if (ret != DM_OK) { + LOGE("HandleNegotiateResult failed ret %{public}d", ret); + context->reason = ERR_DM_CAPABILITY_NEGOTIATE_FAILED; + return ret; + } + if (!context->needBind && !context->needAgreeCredential && context->needAuth) { + return ProcessCredAuth(context); + } + if (context->needBind) { + return ProcessPinBind(context); + } + context->reason = ERR_DM_CAPABILITY_NEGOTIATE_FAILED; + return ERR_DM_FAILED; +} + +int32_t AuthSrcPinNegotiateStartState::ProcessCredAuth(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + JsonObject accesserCredTypeList; + accesserCredTypeList.Parse(context->accesser.credTypeList); + if (accesserCredTypeList.IsDiscarded()) { + LOGE("CredTypeList invalid"); + context->reason = ERR_DM_CAPABILITY_NEGOTIATE_FAILED; + return ERR_DM_FAILED; + } + if (accesserCredTypeList.Contains("identicalCredType")) { + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->accesser.transmitCredentialId = GetCredIdByCredType(context, DM_IDENTICAL_ACCOUNT); + } else if (accesserCredTypeList.Contains("shareCredType")) { + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->accesser.transmitCredentialId = GetCredIdByCredType(context, DM_SHARE); + } else if (accesserCredTypeList.Contains("pointTopointCredType")) { + context->accesser.transmitCredentialId = GetCredIdByCredType(context, DM_POINT_TO_POINT); + } else { + LOGE("credTypeList invalid."); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +std::string AuthSrcPinNegotiateStartState::GetCredIdByCredType(std::shared_ptr context, int32_t credType) +{ + LOGI("credType %{public}d.", credType); + CHECK_NULL_RETURN(context, UNVALID_CREDTID); + if (context->accesser.credentialInfos.find(credType) != context->accesser.credentialInfos.end()) { + LOGE("invalid credType."); + return UNVALID_CREDTID; + } + std::string credInfoStr = context->accesser.credentialInfos[credType]; + LOGI("yangwei credInfoStr %{public}s.", credInfoStr.c_str()); + JsonObject credInfoJson; + credInfoJson.Parse(credInfoStr); + if (credInfoJson.IsDiscarded() || !credInfoJson.Contains(FILED_CRED_ID) || + !credInfoJson[FILED_CRED_ID].IsNumberInteger()) { + LOGE("credInfoStr invalid."); + return UNVALID_CREDTID; + } + return credInfoJson[FILED_CRED_ID].Get(); +} + +int32_t AuthSrcPinNegotiateStartState::ProcessPinBind(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + if (!context->pinNegotiateStarted) { + context->pinNegotiateStarted = true; + CHECK_NULL_RETURN(context->timer, ERR_DM_POINT_NULL); + context->timer->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); + if (context->authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH && + context->authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + LOGE("AuthSrcPinNegotiateStartState::Action authResult not allow"); + context->reason = ERR_DM_BIND_USER_CANCEL; + return ERR_DM_BIND_USER_CANCEL; + } + // import pin code auth always excute + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && + (!context->authTypeList.empty()) && + DmAuthState::IsImportAuthCodeCompatibility(context->authTypeList[0])) { + return NegotiatePinAuth(context, true); + } + } else { + return NegotiatePinAuth(context, false); + } + return ERR_DM_FAILED; +} + +DmAuthStateType AuthSrcPinInputState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_INPUT_STATE; +} + +int32_t AuthSrcPinInputState::ShowStartAuthDialog(std::shared_ptr context) +{ + LOGI("AuthSrcPinInputState::ShowStartAuthDialog start."); + if (DmAuthState::IsScreenLocked()) { + LOGE("AuthSrcPinInputState screen is locked."); + context->reason = ERR_DM_BIND_USER_CANCEL; + return STOP_BIND; + } + + JsonObject jsonObj; + jsonObj[TAG_TARGET_DEVICE_NAME] = context->accessee.deviceName; + jsonObj[TOKENID] = context->accesser.tokenId; + const std::string params = jsonObj.Dump(); + + DmDialogManager::GetInstance().ShowInputDialog(params); + LOGI("AuthSrcPinInputState::ShowStartAuthDialog end."); + return DM_OK; +} + +int32_t AuthSrcPinInputState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcPinInputState::Action start"); + if (context->inputPinAuthFailTimes == 0) { + auto ret = ShowStartAuthDialog(context); + if (ret != DM_OK) { + return ret; + } + } else { + // clear input pin box, and show try again + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); + } + + LOGI("AuthSrcPinInputState::Action waitting user operation"); + // wait for user operation + if (DmEventType::ON_USER_OPERATION != + context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { + LOGI("AuthSrcPinInputState::Action wait ON_USER_OPERATION err"); + return STOP_BIND; + } + + if (context->pinInputResult != USER_OPERATION_TYPE_DONE_PINCODE_INPUT) { + LOGE("AuthSrcPinInputState::Action not USER_OPERATION_TYPE_DONE_PINCODE_INPUT err"); + return STOP_BIND; + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +DmAuthStateType AuthSinkPinNegotiateStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE; +} + +int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr context) +{ + if (!context->pinNegotiateStarted) { + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + context->pinNegotiateStarted = true; + } else { + if (context->authType == DmAuthType::AUTH_TYPE_PIN && + context->inputPinAuthFailTimes < MAX_AUTH_INPUT_PIN_FAIL_TIMES) { + LOGI("AuthSinkPinNegotiateStartState::Action input pin auth err, retry"); + } else { + // try to fallback to next auth type + auto idx = context->currentAuthTypeIdx; + if (idx + 1 >= context->authTypeList.size()) { + LOGE("AuthSinkPinNegotiateStartState::Action all auth type failed"); + context->reason = ERR_DM_AUTH_REJECT; + return ERR_DM_AUTH_REJECT; + } + ++idx; + context->currentAuthTypeIdx = idx; + context->authType = context->authTypeList[idx]; + } + } + // restart pin auth timer + context->timer->DeleteTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK)); + context->timer->StartTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_PIN_AUTH_TIMEOUT_TASK, PIN_AUTH_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { + LOGI("AuthSinkPinNegotiateStartState::Action import auth code"); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { + LOGI("AuthSinkPinNegotiateStartState::Action input pin"); + context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { + LOGI("AuthSinkPinNegotiateStartState::Action ultrasonic pin"); + } else { + LOGE("AuthSrcPinNegotiateStartState::Action authType not support"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +DmAuthStateType AuthSinkPinDisplayState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE; +} + +int32_t AuthSinkPinDisplayState::Action(std::shared_ptr context) +{ + if (context->inputPinAuthFailTimes == 0) { + // gen pincode + AuthSinkStatePinAuthComm::GeneratePincode(context); + // show pincode + return AuthSinkStatePinAuthComm::ShowAuthInfoDialog(context); + } + return DM_OK; +} + +DmAuthStateType AuthSrcPinNegotiateUltrasonicPinState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE; +} + +int32_t AuthSrcPinNegotiateUltrasonicPinState::Action(std::shared_ptr context) +{ + return ERR_DM_FAILED; +} + +DmAuthStateType AuthSinkPinNegotiateUltrasonicPinState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE; +} + +int32_t AuthSinkPinNegotiateUltrasonicPinState::Action(std::shared_ptr context) +{ + return ERR_DM_FAILED; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp new file mode 100644 index 000000000..13bfb140a --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 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 "dm_auth_context.h" + +namespace OHOS { +namespace DistributedHardware { + +std::string DmAuthContext::GetDeviceId(DmAuthSide side) +{ + const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.deviceId : remoteAccess.deviceId; +} + +int32_t DmAuthContext::GetUserId(DmAuthSide side) +{ + const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.userId : remoteAccess.userId; +} + +std::string DmAuthContext::GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope) +{ + const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + const DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? access.lnnCredentialId : access.transmitCredentialId; +} + +std::string DmAuthContext::GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope) +{ + const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + const DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? access.lnnPublicKey : access.transmitPublicKey; +} + +void DmAuthContext::SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId) +{ + DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; + std::string &credId = (authorizedScope == DM_AUTH_SCOPE_USER) ? + access.lnnCredentialId : access.transmitCredentialId; + credId = credentialId; + return; +} + +void DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey) +{ + DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; + std::string &key = (authorizedScope == DM_AUTH_SCOPE_USER) ? + access.lnnPublicKey : access.transmitPublicKey; + key = publicKey; + + return; +} + +std::string DmAuthContext::GetAccountId(DmAuthSide side) +{ + DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.accountId : remoteAccess.accountId; +} + +uint32_t DmAuthContext::GetBindType() +{ + if (accesser.accountId == "ohosAnonymousUid" || accessee.accountId == "ohosAnonymousUid") { + return DM_POINT_TO_POINT; + } else { + return DM_ACROSS_ACCOUNT; + } +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp new file mode 100644 index 000000000..0d4644764 --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -0,0 +1,419 @@ +/* + * Copyright (c) 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 "multiple_user_connector.h" +#include "os_account_manager.h" + +#include "dm_error_type.h" +#include "dm_auth_manager_base.h" + +#ifdef OS_ACCOUNT_PART_EXISTS +#include "os_account_manager.h" +using namespace OHOS::AccountSA; +#endif // OS_ACCOUNT_PART_EXISTS + +namespace OHOS { +namespace DistributedHardware { + +const char* DM_VERSION_5_0_1 = "5.0.1"; +const char* DM_VERSION_5_0_2 = "5.0.2"; +const char* DM_VERSION_5_0_3 = "5.0.3"; +const char* DM_VERSION_5_0_4 = "5.0.4"; +const char* DM_VERSION_5_0_5 = "5.0.5"; +const char* DM_VERSION_5_1_0 = "5.1.0"; +const char* DM_VERSION_5_0_OLD_MAX = "5.0.9"; // Estimated highest version number of the old version + +const char* TAG_DMVERSION = "dmVersion"; +const char* TAG_EDITION = "edition"; +const char* TAG_DATA = "data"; +const char* TAG_DATA_LEN = "dataLen"; +const char* TAG_BUNDLE_NAME = "bundleName"; +const char* TAG_PEER_BUNDLE_NAME = "PEER_BUNDLE_NAME"; +const char* TAG_BIND_LEVEL = "bindLevel"; +const char* TAG_REPLY = "REPLY"; +const char* TAG_APP_THUMBNAIL2 = "appThumbnail"; // Naming Add 2 to resolve conflicts with TAG_APP_THUMBNAIL +const char* TAG_AUTH_FINISH = "isFinish"; +const char* TAG_LOCAL_USERID = "localUserId"; + +const char* APP_OPERATION_KEY = "appOperation"; +const char* TARGET_PKG_NAME_KEY = "targetPkgName"; +const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; +const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; +const char* BUNDLE_NAME_KEY = "bundleName"; + +const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authenticate"; +const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; +const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; +const char* INPUT_TIMEOUT_TASK = "deviceManagerTimer:input"; +const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; +const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; +const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; +const char* WAIT_PIN_AUTH_TIMEOUT_TASK = "deviceManagerTimer:waitPinAuth"; +const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; +const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; +const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK = "deviceManagerTimer:waitSessionClose"; +const char* CLOSE_SESSION_TASK_SEPARATOR = "#"; + +const int32_t AUTHENTICATE_TIMEOUT = 120; +const int32_t CONFIRM_TIMEOUT = 60; +const int32_t NEGOTIATE_TIMEOUT = 10; +const int32_t INPUT_TIMEOUT = 60; +const int32_t ADD_TIMEOUT = 10; +const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; +const int32_t WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; +const int32_t CLONE_CONFIRM_TIMEOUT = 10; +const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_ADD_TIMEOUT = 10; +const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; +const int32_t CLONE_PIN_AUTH_TIMEOUT = 10; +const int32_t HML_SESSION_TIMEOUT = 10; +const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; +const int32_t PIN_AUTH_TIMEOUT = 60; +const int32_t EVENT_TIMEOUT = 5000; // 5000 ms + + +int32_t AuthManagerBase::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGE("AuthenticateDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) +{ + LOGE("UnAuthenticateDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra) +{ + LOGE("UnBindDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGE("OnSessionOpened is not implemented in the current version"); +} + +void AuthManagerBase::OnSessionClosed(const int32_t sessionId) +{ + LOGE("OnSessionClosed is not implemented in the current version"); +} + +void AuthManagerBase::OnDataReceived(const int32_t sessionId, const std::string message) +{ + LOGE("OnDataReceived is not implemented in the current version"); +} + +void AuthManagerBase::OnGroupCreated(int64_t requestId, const std::string &groupId) +{ + LOGE("OnGroupCreated is not implemented in the current version"); +} + +void AuthManagerBase::OnMemberJoin(int64_t requestId, int32_t status) +{ + LOGE("OnMemberJoin is not implemented in the current version"); +} + +int32_t AuthManagerBase::EstablishAuthChannel(const std::string &deviceId) +{ + LOGE("EstablishAuthChannel is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::StartNegotiate(const int32_t &sessionId) +{ + LOGE("StartNegotiate is not implemented in the current version"); +} + +void AuthManagerBase::RespNegotiate(const int32_t &sessionId) +{ + LOGE("RespNegotiate is not implemented in the current version"); +} + +void AuthManagerBase::SendAuthRequest(const int32_t &sessionId) +{ + LOGE("SendAuthRequest is not implemented in the current version"); +} + +int32_t AuthManagerBase::StartAuthProcess(const int32_t &action) +{ + LOGE("StartAuthProcess is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::StartRespAuthProcess() +{ + LOGE("StartRespAuthProcess is not implemented in the current version"); +} + +int32_t AuthManagerBase::CreateGroup() +{ + LOGE("CreateGroup is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::ProcessPincode(int32_t pinCode) +{ + LOGE("ProcessPincode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +std::string AuthManagerBase::GetConnectAddr(std::string deviceId) +{ + LOGE("GetConnectAddr is not implemented in the current version"); + return ""; +} + +int32_t AuthManagerBase::JoinNetwork() +{ + LOGE("JoinNetwork is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::AuthenticateFinish() +{ + LOGE("AuthenticateFinish is not implemented in the current version"); +} + +bool AuthManagerBase::GetIsCryptoSupport() +{ + LOGE("GetIsCryptoSupport is not implemented in the current version"); + return false; +} + +int32_t AuthManagerBase::SetAuthRequestState(std::shared_ptr authRequestState) +{ + LOGE("SetAuthRequestState is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::SetAuthResponseState(std::shared_ptr authResponseState) +{ + LOGE("SetAuthResponseState is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::GetPinCode(int32_t &code) +{ + LOGE("GetPinCode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +std::string AuthManagerBase::GenerateGroupName() +{ + LOGE("GenerateGroupName is not implemented in the current version"); + return ""; +} + +void AuthManagerBase::HandleAuthenticateTimeout(std::string name) +{ + LOGE("HandleAuthenticateTimeout is not implemented in the current version"); +} + +int32_t AuthManagerBase::GeneratePincode() +{ + LOGE("GeneratePincode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::ShowConfigDialog() +{ + LOGE("ShowConfigDialog is not implemented in the current version"); +} + +void AuthManagerBase::ShowAuthInfoDialog(bool authDeviceError) +{ + LOGE("ShowAuthInfoDialog is not implemented in the current version"); +} + +void AuthManagerBase::ShowStartAuthDialog() +{ + LOGE("ShowStartAuthDialog is not implemented in the current version"); +} + +int32_t AuthManagerBase::OnUserOperation(int32_t action, const std::string ¶ms) +{ + LOGE("OnUserOperation is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::SetPageId(int32_t pageId) +{ + LOGE("SetPageId is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::SetReasonAndFinish(int32_t reason, int32_t state) +{ + LOGE("SetReasonAndFinish is not implemented in the current version"); + return ERR_DM_FAILED; +} + +bool AuthManagerBase::IsIdenticalAccount() +{ + LOGE("IsIdenticalAccount is not implemented in the current version"); + return false; +} + +int32_t AuthManagerBase::RegisterUiStateCallback(const std::string pkgName) +{ + LOGE("RegisterUiStateCallback is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::UnRegisterUiStateCallback(const std::string pkgName) +{ + LOGE("UnRegisterUiStateCallback is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::ImportAuthCode(const std::string &pkgName, const std::string &authCode) +{ + LOGE("ImportAuthCode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam, int sessionId, int64_t logicalSessionId) +{ + LOGE("BindTarget is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::RegisterAuthenticationType(int32_t authenticationType) +{ + LOGE("RegisterAuthenticationType is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::StopAuthenticateDevice(const std::string &pkgName) +{ + LOGE("StopAuthenticateDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::DeleteGroup(const std::string &pkgName, const std::string &deviceId) +{ + LOGE("DeleteGroup is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::GetReason() +{ + LOGE("GetReason is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam) +{ + LOGE("GetBindTargetParams is not implemented in the current version"); + return; +} + +void AuthManagerBase::SetBindTargetParams(const PeerTargetId &targetId) +{ + LOGE("SetBindTargetParams is not implemented in the current version"); + return; +} + +void AuthManagerBase::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback) +{ + LOGE("RegisterCleanNotifyCallback is not implemented in the current version"); + return; +} + +std::string AuthManagerBase::ConvertSrcVersion(const std::string &version, const std::string &edition) +{ + std::string srcVersion = ""; + if (version == "" && edition != "") { + srcVersion = edition; + } else if (version == "" && edition == "") { + srcVersion = DM_VERSION_5_1_0; + } else if (version != "" && edition == "") { + srcVersion = version; + } + LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.", + version.c_str(), edition.c_str(), srcVersion.c_str()); + return srcVersion; +} + +// Scenario 1: The remote side specifies userId -> Verify if it is a front-end user +// Scenario 2: The remote side does not specify userId +// Scenario 2.1: Single user -> Use the current unique front-end user +// Scenario 2.2: Multiple users -> Use the current main screen user +int32_t AuthManagerBase::DmGetUserId(int32_t displayId) +{ + int32_t ret; + int32_t userId = -1; + + std::vector userIds; + ret = MultipleUserConnector::GetForegroundUserIds(userIds); + if (ret != DM_OK) { + LOGE("RespQueryTokenId: GetForegroundUserIds failed, ret: %{public}d", ret); + return -1; + } + // Scenario 1: The remote side specifies userId -> Verify if it is a front-end user + // Scenario 2: The remote side does not specify userId + // Scenario 2.1: Single user -> Use the current unique front-end user + // Scenario 2.2: Multiple users -> Use the current main screen user + if (userIds.size() == 0) { + LOGE("RespQueryTokenId: GetForegroundUserIds no foreground users"); + return -1; + } + + if (displayId != -1) { + ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(displayId, userId); + if (ret != DM_OK) { + LOGE("RespQueryTokenId: fail to get userId by displayId %{public}d", displayId); + return -1; + } + return userId; + } + if (userIds.size() == 1) { + return userIds[0]; + } else { + // If userIds.size() > 1, we need to find the main screen user +#ifdef OS_ACCOUNT_PART_EXISTS + ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId); + if (ret != DM_OK) { + LOGE("AuthManagerBase::DmGetUserId: get foreground user failed in multi users with error %{public}d", ret); + return -1; + } + return userId; +#else + LOGE("AuthManagerBase::DmGetUserId: get foreground user failed because no OsAcccountManager"); + return -1; +#endif + } +} + +bool AuthManagerBase::IsTransferReady() +{ + return isTransferReady_; +} + +void AuthManagerBase::SetTransferReady(bool version) +{ + isTransferReady_ = version; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp new file mode 100644 index 000000000..9a37e9e9b --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -0,0 +1,1406 @@ +/* + * Copyright (c) 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 +#include +#include +#include +#include "dm_anonymous.h" +#include "dm_auth_context.h" +#include "dm_auth_message_processor.h" +#include "distributed_device_profile_client.h" +#include "deviceprofile_connector.h" +#include "service_info_profile.h" +#include "service_info_unique_key.h" +#include "dm_log.h" +#include "dm_constants.h" +#include "dm_anonymous.h" +#include "access_control_profile.h" +#include "dm_auth_manager_base.h" +#include "dm_auth_context.h" +#include "dm_auth_state_machine.h" +#include "dm_crypto.h" + +namespace OHOS { +namespace DistributedHardware { + +const char* TAG_LNN_PUBLICK_KEY = "lnnPublicKey"; +const char* TAG_TRANSMIT_PUBLICK_KEY = "transmitPublicKey"; +const char* TAG_LNN_CREDENTIAL_ID = "lnnCredentialId"; +const char* TAG_TRANSMIT_CREDENTIAL_ID = "transmitCredentialId"; +const char* TAG_AUTH_RESULT = "authResult"; +const char* TAG_AUTH_TYPE_LIST = "authTypeList"; +const char* TAG_CURRENT_AUTH_TYPE_IDX = "currentAuthTypeIdx"; + +// IS interface input parameter json format string key +const char* TAG_METHOD = "method"; +const char* TAG_PEER_USER_SPACE_ID = "peerUserSpaceId"; +const char* TAG_SUBJECT = "subject"; +const char* TAG_CRED_TYPE = "credType"; +const char* TAG_KEY_FORMAT = "keyFormat"; +const char* TAG_ALGORITHM_TYPE = "algorithmType"; +const char* TAG_PROOF_TYPE = "proofType"; +const char* TAG_KEY_VALUE = "keyValue"; +const char* TAG_AUTHORIZED_SCOPE = "authorizedScope"; +const char* TAG_AUTHRIZED_APP_LIST = "authorizedAppList"; +const char* TAG_CREDENTIAL_OWNER = "credOwner"; +const char* TAG_SYNC = "syncMessage"; +const char* TAG_ACCESS = "dmAccess"; +const char* TAG_PROXY = "proxy"; +const char* TAG_ACL = "accessControlTable"; +const char* TAG_ACCESSER = "dmAccesser"; +const char* TAG_ACCESSEE = "dmAccessee"; +const char* TAG_SERVICEINFO = "serviceInfo"; +// The local SK information is synchronized to the remote end to construct acl-accesser/accessee. +const char* TAG_TRANSMIT_SK_ID = "accessAppSKId"; +const char* TAG_LNN_SK_ID = "accessUserSKId"; +const char* TAG_TRANSMIT_SK_TIMESTAMP = "accessAppSKTimeStamp"; +const char* TAG_LNN_SK_TIMESTAMP = "accessUserSKTimeStamp"; +const char* TAG_USER_ID = "userId"; +const char* TAG_TOKEN_ID = "tokenId"; +const char* TAG_ISSUER = "issuer"; + +const char* TAG_DEVICE_VERSION = "deviceVersion"; +const char* TAG_DEVICE_NAME = "deviceName"; +const char* TAG_DEVICE_ID_HASH = "deviceIdHash"; +const char* TAG_USER_ID_HASH = "userIdHash"; +const char* TAG_ACCOUNT_ID_HASH = "accountIdHash"; +const char* TAG_TOKEN_ID_HASH = "tokenIdHash"; +const char* TAG_SESSION_NAME = "sessionName"; +const char* TAG_ACL_CHECKSUM = "aclCheckSum"; +const char* TAG_COMPRESS_ORI_LEN = "compressOriLen"; +const char* TAG_COMPRESS = "compressMsg"; +const char* TAG_STATE = "state"; +const char* TAG_REASON = "reason"; +const char* TAG_PEER_USER_ID = "peerUserId"; +const char* TAG_PEER_DISPLAY_ID = "peerDisplayId"; +const char* TAG_EXTRA_INFO = "extraInfo"; +const char* TAG_ACL_LIST = "aclList"; +const char* TAG_CERT_TYPE_LIST = "certTypeList"; + +const char* TAG_IS_ONLINE = "isOnline"; +const char* TAG_IS_AUTHED = "isAuthed"; +const char* TAG_CREDENTIAL_INFO = "credentialInfo"; +const char* TAG_CERT_INFO = "certInfo"; +const char* TAG_LANGUAGE = "language"; + +// Accesser table content is used for ACL synchronization. +const char* TAG_ACCESSER_DEVICE_ID = "accesserDeviceId"; +const char* TAG_ACCESSER_USER_ID = "accesserUserId"; +const char* TAG_ACCESSER_ACOUNT_ID = "accesserAcountId"; +const char* TAG_ACCESSER_TOKEN_ID = "accesserTokenId"; +const char* TAG_ACCESSER_SERVICE_NAME = "accesserServiceName"; +const char* TAG_ACCESSER_BUNDLE_NAME = "accesserBundleName"; +const char* TAG_ACCESSER_HAP_SIGNATURE = "accesserHapSignature"; +const char* TAG_ACCESSER_BIND_LEVEL = "accesserBindLevel"; +const char* TAG_ACCESSER_CREDENTIAL_ID = "accesserCredetialId"; +const char* TAG_ACCESSER_STATUS = "accesserStatus"; +const char* TAG_ACCESSER_SK_ID = "accesserSessionKeyId"; +const char* TAG_ACCESSER_SK_TIMESTAMP = "accesserSKTimeStamp"; + +// Accessee table content is used for ACL synchronization. +const char* TAG_ACCESSEE_DEVICE_ID = "accesseeDeviceId"; +const char* TAG_ACCESSEE_USER_ID = "accesseeUserId"; +const char* TAG_ACCESSEE_ACOUNT_ID = "accesseeAcountId"; +const char* TAG_ACCESSEE_TOKEN_ID = "accesseeTokenId"; +const char* TAG_ACCESSEE_SERVICE_NAME = "accesseeServiceName"; +const char* TAG_ACCESSEE_BUNDLE_NAME = "accesseeBundleName"; +const char* TAG_ACCESSEE_HAP_SIGNATURE = "accesseeHapSignature"; +const char* TAG_ACCESSEE_BIND_LEVEL = "accesseeBindLevel"; +const char* TAG_ACCESSEE_CREDENTIAL_ID = "accesseeCredetialId"; +const char* TAG_ACCESSEE_STATUS = "accesseeStatus"; +const char* TAG_ACCESSEE_SK_ID = "accesseeSessionKeyId"; +const char* TAG_ACCESSEE_SK_TIMESTAMP = "accesseeSKTimeStamp"; + +namespace { + +constexpr const int32_t DM_HASH_LEN = 32; +const char* TAG_DEVICE_TYPE = "DEVICETYPE"; + +void ParseDmAccessToSync(const std::string &jsonString, DmAccess &access) +{ + JsonObject accessjson(jsonString); + DmAccessToSync srcAccessToSync = accessjson.Get(); + access.deviceName = srcAccessToSync.deviceName; + access.deviceId = srcAccessToSync.deviceId; + access.userId = srcAccessToSync.userId; + access.accountId = srcAccessToSync.accountId; + access.tokenId = srcAccessToSync.tokenId; + access.bundleName = srcAccessToSync.bundleName; + access.bindLevel = srcAccessToSync.bindLevel; + access.sessionKeyId = srcAccessToSync.sessionKeyId; + access.skTimeStamp = srcAccessToSync.skTimeStamp; + return; +} + +int32_t ParaseAclChecksumList(const std::string &jsonString, DmAccess &access) +{ + JsonObject aclChecksumjson(jsonString); + if (aclChecksumjson.IsDiscarded()) { + LOGE("ParseSyncMessage aclChecksumjson error"); + return ERR_DM_FAILED; + } + if (!aclChecksumjson[TAG_ACCESSER].IsArray()) { + LOGE("ParseSyncMessage TAG_ACCESSER error"); + return ERR_DM_FAILED; + } + aclChecksumjson[TAG_ACCESSER].Get(access.accesserStrList); + if (!aclChecksumjson[TAG_ACCESSEE].IsArray()) { + LOGE("ParseSyncMessage TAG_ACCESSEE error"); + return ERR_DM_FAILED; + } + aclChecksumjson[TAG_ACCESSEE].Get(access.accesseeStrList); + return DM_OK; +} + +bool IsMessageValid(const JsonItemObject &jsonObject) +{ + if (jsonObject.IsDiscarded()) { + LOGE("DmAuthMessageProcessor::ParseMessage failed, decodeRequestAuth jsonStr error"); + return false; + } + if (!jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { + LOGE("DmAuthMessageProcessor::ParseMessage failed, message type error."); + return false; + } + return true; +} + +} + +int32_t DmAuthMessageProcessor::SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen) +{ + if (cryptoMgr_ == nullptr) { + LOGE("DmAuthMessageProcessor::SaveSessionKey failed, cryptoMgr_ is nullptr."); + return ERR_DM_FAILED; + } + return cryptoMgr_->ProcessSessionKey(sessionKey, keyLen); +} + +int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t &skId) +{ + if (cryptoMgr_ == nullptr) { + LOGE("DmAuthMessageProcessor::SaveSessionKeyToDP failed, cryptoMgr_ is nullptr."); + return ERR_DM_FAILED; + } + return DeviceProfileConnector::GetInstance().PutSessionKey(cryptoMgr_->GetSessionKey(), skId); +} + +void DmAuthMessageProcessor::SetAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::AccessControlProfile &profile) +{ + uint32_t authenticationType = ALLOW_AUTH_ONCE; + if (context->authResult == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + authenticationType = ALLOW_AUTH_ALWAYS; + } + profile.SetAuthenticationType(authenticationType); + profile.SetStatus(ACTIVE); + profile.SetDeviceIdType((int32_t)DistributedDeviceProfile::DeviceIdType::UDID); +} + +void DmAuthMessageProcessor::SetTransmitAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee) +{ + accesser.SetAccesserDeviceId(context->accesser.deviceId); + accesser.SetAccesserUserId(context->accesser.userId); + accesser.SetAccesserAccountId(context->accesser.accountId); + accesser.SetAccesserTokenId(context->accesser.tokenId); + accesser.SetAccesserBundleName(context->accesser.bundleName); + accesser.SetAccesserDeviceName(context->accesser.deviceName); + accesser.SetAccesserCredentialIdStr(context->accesser.transmitCredentialId); + accesser.SetAccesserSessionKeyId(context->accesser.transmitSessionKeyId); + accesser.SetAccesserSKTimeStamp(context->accesser.transmitSkTimeStamp); + accesser.SetAccesserExtraData(context->accesser.extraInfo); + accessee.SetAccesseeDeviceId(context->accessee.deviceId); + accessee.SetAccesseeUserId(context->accessee.userId); + accessee.SetAccesseeAccountId(context->accessee.accountId); + accessee.SetAccesseeTokenId(context->accessee.tokenId); + accessee.SetAccesseeBundleName(context->accessee.bundleName); + accessee.SetAccesseeDeviceName(context->accessee.deviceName); + accessee.SetAccesseeCredentialIdStr(context->accessee.transmitCredentialId); // 依赖dp + accessee.SetAccesseeSessionKeyId(context->accessee.transmitSessionKeyId); + accessee.SetAccesseeSKTimeStamp(context->accessee.transmitSkTimeStamp); + accessee.SetAccesseeExtraData(context->accessee.extraInfo); +} + +void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee) +{ + accesser.SetAccesserDeviceId(context->accesser.deviceId); + accesser.SetAccesserUserId(context->accesser.userId); + accesser.SetAccesserAccountId(context->accesser.accountId); + accesser.SetAccesserTokenId(0); + accesser.SetAccesserDeviceName(context->accesser.deviceName); + accesser.SetAccesserCredentialIdStr(context->accesser.lnnCredentialId); + accesser.SetAccesserSessionKeyId(context->accesser.lnnSessionKeyId); + accesser.SetAccesserSKTimeStamp(context->accesser.lnnSkTimeStamp); + accesser.SetAccesserExtraData(context->accesser.extraInfo); + accessee.SetAccesseeDeviceId(context->accessee.deviceId); + accessee.SetAccesseeUserId(context->accessee.userId); + accessee.SetAccesseeAccountId(context->accessee.accountId); + accessee.SetAccesseeTokenId(0); + accessee.SetAccesseeDeviceName(context->accessee.deviceName); + accessee.SetAccesseeCredentialIdStr(context->accessee.lnnCredentialId); + accessee.SetAccesseeSessionKeyId(context->accessee.lnnSessionKeyId); + accessee.SetAccesseeSKTimeStamp(context->accessee.lnnSkTimeStamp); + accessee.SetAccesseeExtraData(context->accessee.extraInfo); +} + +int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr context, + DmAccess &access, std::string trustDeviceId) +{ + LOGI("Start."); + DistributedDeviceProfile::Accesser accesser; + DistributedDeviceProfile::Accessee accessee; + SetLnnAccessControlList(context, accesser, accessee); + DistributedDeviceProfile::AccessControlProfile profile; + SetAccessControlList(context, profile); + profile.SetBindLevel(access.bindLevel); + profile.SetTrustDeviceId(trustDeviceId); + profile.SetDeviceIdHash(access.deviceIdHash); + profile.SetBindType(access.lnnBindType); + profile.SetAccessee(accessee); + profile.SetAccesser(accesser); + int32_t ret = + DistributedDeviceProfile::DistributedDeviceProfileClient::GetInstance().PutAccessControlProfile(profile); + if (ret != DM_OK) { + LOGE("PutAccessControlProfile failed."); + } + SetTransmitAccessControlList(context, accesser, accessee); + profile.SetBindType(access.transmitBindType); + profile.SetAccessee(accessee); + profile.SetAccesser(accesser); + ret = + DistributedDeviceProfile::DistributedDeviceProfileClient::GetInstance().PutAccessControlProfile(profile); + if (ret != DM_OK) { + LOGE("PutAccessControlProfile failed."); + } + return ret; +} + +DmAuthMessageProcessor::DmAuthMessageProcessor() +{ + LOGI("DmAuthMessageProcessor constructor"); + cryptoMgr_ = std::make_shared(); + createMessageFuncMap_ = { + {DmMessageType::MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateRespNegotiateMessage}, + {DmMessageType::MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageReqUserConfirm}, + {DmMessageType::MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageRespUserConfirm}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqPinAuthStart}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageRespPinAuthStart}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, + &DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageReqCredExchange}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageRspCredExchange}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqCredAuthStart}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, + &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, + &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {DmMessageType::MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::CreateSyncMessage}, + {DmMessageType::MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::CreateMessageSyncResp}, + {DmMessageType::MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, + {DmMessageType::MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, + }; + paraseMessageFuncMap_ = { + {DmMessageType::MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageRespAclNegotiate}, + {DmMessageType::MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageReqUserConfirm}, + {DmMessageType::MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageRespUserConfirm}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageReqPinAuthStart}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageRespPinAuthStart}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, + &DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageReqCredExchange}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageRspCredExchange}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseAuthStartMessage}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, + &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {DmMessageType::MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncReq}, + {DmMessageType::MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncResp}, + {DmMessageType::MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::ParseMessageSinkFinish}, + {DmMessageType::MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::ParseMessageSrcFinish}, + }; + LOGI("DmAuthMessageProcessor constructor leave."); +} + +DmAuthMessageProcessor::~DmAuthMessageProcessor() +{ + if (cryptoMgr_ != nullptr) { + cryptoMgr_->ClearSessionKey(); + cryptoMgr_ = nullptr; + } +} + +int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr context, const std::string &message) +{ + JsonObject jsonObject(message); + if (context == nullptr || !IsMessageValid(jsonObject)) { + return ERR_DM_FAILED; + } + DmMessageType msgType = static_cast(jsonObject[TAG_MSG_TYPE].Get()); + context->msgType = msgType; + LOGI("DmAuthMessageProcessor::ParseMessage message type %{public}d", context->msgType); + LOGI("yangwei DmAuthMessageProcessor::ParseMessage message is %{public}s", message.c_str()); + auto itr = paraseMessageFuncMap_.find(msgType); + if (itr == paraseMessageFuncMap_.end()) { + LOGI("DmAuthMessageProcessor::ParseMessage message type error %{public}d", context->msgType); + return ERR_DM_FAILED; + } + return (this->*(itr->second))(jsonObject, context); +} + +static std::vector stringToVectorAuthType(const std::string& str) +{ + std::vector vec; + std::istringstream iss(str); + int32_t num; + while (iss >> num) { + vec.push_back(static_cast(num)); + } + return vec; +} + +static std::string vectorAuthTypeToString(const std::vector& vec) +{ + std::ostringstream oss; + for (size_t i = 0; i < vec.size(); ++i) { + oss << static_cast(vec[i]); + if (i != vec.size() - 1) { + oss << " "; // Add a separator (e.g. space) + } + } + return oss.str(); +} + +int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject.IsDiscarded() || !jsonObject.Contains(TAG_DATA) || !jsonObject[TAG_DATA].IsString()) { + LOGE("DmAuthMessageProcessor::ParseMessageNegotiateTransmit Unlegal json string failed"); + return ERR_DM_FAILED; + } + + context->transmitData = jsonObject[TAG_DATA].Get(); + + switch (context->msgType) { + case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 + context->authStateMachine->TransitionTo(std::make_shared()); + break; + case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 + context->authStateMachine->TransitionTo(std::make_shared()); + break; + case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 + context->authStateMachine->TransitionTo(std::make_shared()); + break; + default: + return ERR_DM_FAILED; + } + + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject.IsDiscarded() || !jsonObject[TAG_DATA].IsString()) { + LOGE("DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate failed, decodeRequestAuth jsonStr error"); + return ERR_DM_FAILED; + } + + context->transmitData = jsonObject[TAG_DATA].Get(); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject.IsDiscarded() || !jsonObject[TAG_DATA].IsString()) { + LOGE("DecodeRequestAuth jsonStr error"); + return ERR_DM_FAILED; + } + + std::string plainText; + if (cryptoMgr_->DecryptMessage(jsonObject[TAG_DATA].Get(), plainText) != DM_OK) { + LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, decrypt data failed."); + return ERR_DM_FAILED; + } + JsonObject jsonData(plainText); + + // First authentication, parse lnn public key + if (!context->isOnline) { + if (!jsonData[TAG_LNN_PUBLICK_KEY].IsString()) { + LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, first auth, no lnnPublicKey."); + return ERR_DM_FAILED; + } + context->accesser.lnnPublicKey = jsonData[TAG_LNN_PUBLICK_KEY].Get(); + } + + if (!jsonData[TAG_TRANSMIT_PUBLICK_KEY].IsString() || + !jsonData[TAG_DEVICE_ID].IsString() || + !jsonData[TAG_PEER_USER_SPACE_ID].IsNumberInteger() || + !jsonData[TAG_TOKEN_ID].IsNumberInteger()) { + LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange, MSG_TYPE_REQ_CREDENTIAL_EXCHANGE message error."); + return ERR_DM_FAILED; + } + context->accesser.transmitPublicKey = jsonData[TAG_TRANSMIT_PUBLICK_KEY].Get(); + context->accesser.deviceId = jsonData[TAG_DEVICE_ID].Get(); + context->accesser.userId = jsonData[TAG_PEER_USER_SPACE_ID].Get(); + context->accesser.tokenId = jsonData[TAG_TOKEN_ID].Get(); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &jsonObject, + std::shared_ptr context) +{ + LOGI("DmAuthMessageProcessor::ParseMessageRspCredExchange start."); + if (jsonObject.IsDiscarded() || !jsonObject[TAG_DATA].IsString()) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange, DecodeRequestAuth jsonStr error"); + return ERR_DM_FAILED; + } + + std::string plainText; + if (cryptoMgr_->DecryptMessage(jsonObject[TAG_DATA].Get(), plainText) != DM_OK) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange error, decrypt data failed."); + return ERR_DM_FAILED; + } + + LOGI("DmAuthMessageProcessor::ParseMessageRspCredExchange plainText=%{public}s", plainText.c_str()); + + JsonObject jsonData(plainText); + + // First authentication, parse lnn public key + std::string tmpString; + if (!context->isOnline) { + if (!jsonData[TAG_LNN_PUBLICK_KEY].IsString()) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, first auth but no lnnPublicKey."); + return ERR_DM_FAILED; + } + context->accessee.lnnPublicKey = jsonData[TAG_LNN_PUBLICK_KEY].Get(); + } + + // First authentication, parse transmit public key + if (!jsonData[TAG_TRANSMIT_PUBLICK_KEY].IsString() || + !jsonData[TAG_DEVICE_ID].IsString() || + !jsonData[TAG_PEER_USER_SPACE_ID].IsNumberInteger() || + !jsonData[TAG_TOKEN_ID].IsNumberInteger()) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, decode MSG_TYPE_RESP_CREDENTIAL_EXCHANGE " + "message error."); + return ERR_DM_FAILED; + } + context->accessee.transmitPublicKey = jsonData[TAG_TRANSMIT_PUBLICK_KEY].Get(); + context->accessee.deviceId = jsonData[TAG_DEVICE_ID].Get(); + context->accessee.userId = jsonData[TAG_PEER_USER_SPACE_ID].Get(); + context->accessee.tokenId = jsonData[TAG_TOKEN_ID].Get(); + + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::shared_ptr context) +{ + LOGI("DmAuthMessageProcessor::CreateMessage start. msgType is %{public}d", msgType); + JsonObject jsonObj; + jsonObj[TAG_MSG_TYPE] = msgType; + jsonObj[DM_TAG_LOGICAL_SESSION_ID] = context->logicalSessionId; + auto itr = createMessageFuncMap_.find(msgType); + if (itr == createMessageFuncMap_.end()) { + LOGE("DmAuthMessageProcessor::CreateMessage msgType %{public}d error.", msgType); + return ""; + } + int32_t ret = (this->*(itr->second))(context, jsonObj); + LOGI("DmAuthMessageProcessor::CreateMessage start. message is %{public}s", jsonObj.Dump().c_str()); + return (ret == DM_OK) ? jsonObj.Dump() : ""; +} + +int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr context, + JsonObject &jsonObject) +{ + std::string encryptMsg; + jsonObject[TAG_DATA] = context->transmitData; + return DM_OK; +} + +// Create 80 message. +int32_t DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) +{ + jsonObject[TAG_SESSION_NAME] = context->sessionName; + + jsonObject[TAG_DMVERSION] = context->accesser.dmVersion; + jsonObject[TAG_USER_ID] = context->accesser.userId; + jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; + jsonObject[TAG_DEVICE_ID_HASH] = context->accesser.deviceIdHash; + jsonObject[TAG_USER_ID_HASH] = context->accesser.userIdHash; + jsonObject[TAG_ACCOUNT_ID_HASH] = context->accesser.accountIdHash; + jsonObject[TAG_TOKEN_ID_HASH] = context->accesser.tokenIdHash; + jsonObject[TAG_BUNDLE_NAME] = context->accesser.bundleName; + jsonObject[TAG_EXTRA_INFO] = context->accesser.extraInfo; + + jsonObject[TAG_PEER_BUNDLE_NAME] = context->accessee.bundleName; + jsonObject[TAG_PEER_DISPLAY_ID] = context->accessee.displayId; + + return DM_OK; +} + +// Create 90 message. +int32_t DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptr context, + JsonObject &jsonObject) +{ + jsonObject[TAG_DEVICE_VERSION] = context->accessee.dmVersion; + jsonObject[TAG_DEVICE_NAME] = context->accessee.deviceName; + + jsonObject[TAG_DEVICE_ID_HASH] = context->accessee.deviceIdHash; + jsonObject[TAG_USER_ID_HASH] = context->accessee.userIdHash; + jsonObject[TAG_ACCOUNT_ID_HASH] = context->accessee.accountIdHash; + jsonObject[TAG_TOKEN_ID_HASH] = context->accessee.tokenIdHash; + + jsonObject[TAG_ACL_LIST] = context->accessee.aclList; + jsonObject[TAG_CERT_TYPE_LIST] = context->accessee.credTypeList; + jsonObject[TAG_LANGUAGE] = context->accessee.language; + jsonObject[TAG_EXTRA_INFO] = context->accessee.extraInfo; + jsonObject[TAG_IS_ONLINE] = context->accesser.isOnline; + + return DM_OK; +} + +// Create 140 message. +int32_t DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptr context, + JsonObject &jsonObject) +{ + JsonObject jsonData; + if (!context->isOnline) { + jsonData[TAG_LNN_PUBLICK_KEY] = context->accesser.lnnPublicKey; + } + jsonData[TAG_TRANSMIT_PUBLICK_KEY] = context->accesser.transmitPublicKey; + jsonData[TAG_DEVICE_ID] = context->accesser.deviceId; + jsonData[TAG_PEER_USER_SPACE_ID] = context->accesser.userId; + jsonData[TAG_TOKEN_ID] = context->accesser.tokenId; + + std::string plainText = jsonData.Dump(); + std::string cipherText; + int32_t ret = cryptoMgr_->EncryptMessage(plainText, cipherText); + if (ret != DM_OK) { + LOGI("DmAuthMessageProcessor::CreateMessageReqCredExchange encryptMessage failed."); + return ret; + } + jsonObject[TAG_DATA] = cipherText; + return ret; +} + +// Create 150 message. +int32_t DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptr context, + JsonObject &jsonObject) +{ + LOGI("DmAuthMessageProcessor::CreateMessageRspCredExchange start."); + JsonObject jsonData; + if (!context->isOnline) { + jsonData[TAG_LNN_PUBLICK_KEY] = context->accessee.lnnPublicKey; + } + jsonData[TAG_TRANSMIT_PUBLICK_KEY] = context->accessee.transmitPublicKey; + jsonData[TAG_DEVICE_ID] = context->accessee.deviceId; + jsonData[TAG_PEER_USER_SPACE_ID] = context->accessee.userId; + jsonData[TAG_TOKEN_ID] = context->accessee.tokenId; + + std::string plainText = jsonData.Dump(); + std::string cipherText; + LOGI("DmAuthMessageProcessor::CreateMessageRspCredExchange plainText=%{public}s", plainText.c_str()); + int32_t ret = cryptoMgr_->EncryptMessage(plainText, cipherText); + if (ret != DM_OK) { + LOGI("DmAuthMessageProcessor::CreateMessageRspCredExchange encryptMessage failed."); + return ret; + } + jsonObject[TAG_DATA] = cipherText; + return ret; +} + +// Create 160 message. +int32_t DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr context, + JsonObject &jsonObject) +{ + std::string onTransmitData; + + JsonObject jsonData; + jsonObject[TAG_DATA] = context->transmitData; + return DM_OK; +} + +bool DmAuthMessageProcessor::ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl, + std::vector &accesserStrList, std::vector &accesseeStrList) +{ + uint8_t accesserHash[DM_HASH_LEN] = {0}; + std::string accesserStr = AccesserToStr(acl); + Crypto::DmGenerateStrHash(accesserStr.data(), accesserStr.size(), accesserHash, DM_HASH_LEN, 0); + auto accesserIter = find(accesserStrList.begin(), accesserStrList.end(), + std::string(reinterpret_cast(accesserHash))); + + uint8_t accesseeHash[DM_HASH_LEN] = {0}; + std::string accesseeStr = AccesseeToStr(acl); + Crypto::DmGenerateStrHash(accesseeStr.data(), accesseeStr.size(), accesseeHash, DM_HASH_LEN, 0); + auto accesseeIter = find(accesseeStrList.begin(), accesseeStrList.end(), + std::string(reinterpret_cast(accesseeHash))); + return (accesserIter != accesserStrList.end()) && (accesseeIter != accesseeStrList.end()); +} + +// Create 190 message. +int32_t DmAuthMessageProcessor::CreateMessageSyncResp(std::shared_ptr context, + JsonObject &jsonObject) +{ + DmAccess access; + if (context->direction == DM_AUTH_SINK) { + access = context->accessee; + } else { + access = context->accesser; + } + + std::string encSyncMsg; + int32_t ret = EncryptSyncMessage(context, access, encSyncMsg); + if (ret != DM_OK) { + LOGE("DmAuthMessageProcessor::CreateMessageSyncResp encrypt failed"); + return ret; + } + jsonObject[TAG_SYNC] = encSyncMsg; + return ret; +} + +// Create 200 message. +int32_t DmAuthMessageProcessor::CreateMessageFinish(std::shared_ptr context, + JsonObject &jsonObject) +{ + jsonObject[TAG_REPLY] = context->reply; + jsonObject[TAG_STATE] = context->state; + jsonObject[TAG_REASON] = context->reason; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr &context, + DmAccess &access, JsonObject &jsonObject) +{ + // transmit session key is mandatory + if (!jsonObject[TAG_TRANSMIT_SK_ID].IsString()) { + LOGE("ParseSyncMessage TAG_TRANSMIT_SK_ID error"); + return ERR_DM_FAILED; + } + access.transmitSessionKeyId = std::atoi(jsonObject[TAG_TRANSMIT_SK_ID].Get().c_str()); + + if (!jsonObject[TAG_TRANSMIT_SK_TIMESTAMP].IsString()) { + LOGE("ParseSyncMessage TAG_TRANSMIT_SK_TIMESTAMP error"); + return ERR_DM_FAILED; + } + access.transmitSkTimeStamp = std::atoi(jsonObject[TAG_TRANSMIT_SK_TIMESTAMP].Get().c_str()); + + if (!jsonObject[TAG_TRANSMIT_CREDENTIAL_ID].IsString()) { + LOGE("ParseSyncMessage TAG_TRANSMIT_CREDENTIAL_ID error"); + return ERR_DM_FAILED; + } + access.transmitCredentialId = jsonObject[TAG_TRANSMIT_CREDENTIAL_ID].Get().c_str(); + + // lnn session key is optional + if (jsonObject[TAG_LNN_SK_ID].IsString()) { + access.lnnSessionKeyId = std::atoi(jsonObject[TAG_LNN_SK_ID].Get().c_str()); + } + if (jsonObject[TAG_LNN_SK_TIMESTAMP].IsString()) { + access.lnnSkTimeStamp = std::atoi(jsonObject[TAG_LNN_SK_TIMESTAMP].Get().c_str()); + } + + if (jsonObject[TAG_LNN_CREDENTIAL_ID].IsString()) { + access.lnnCredentialId = jsonObject[TAG_LNN_CREDENTIAL_ID].Get().c_str(); + } + + if (!jsonObject[TAG_DMVERSION].IsString()) { + LOGE("ParseSyncMessage TAG_DMVERSION error"); + return ERR_DM_FAILED; + } + + access.dmVersion = jsonObject[TAG_DMVERSION].Get(); + if (!jsonObject[TAG_ACCESS].IsString()) { + LOGE("ParseSyncMessage TAG_ACCESS error"); + return ERR_DM_FAILED; + } + std::string srcAccessStr = jsonObject[TAG_ACCESS].Get(); + // Parse into access + ParseDmAccessToSync(srcAccessStr, access); + if (jsonObject[TAG_PROXY].IsString()) { // Reserved field + std::string proxyInfo = jsonObject[TAG_PROXY].Get(); + } + if (jsonObject[TAG_SERVICEINFO].IsString()) { // sp not yet uploaded + std::string serviceInfo = jsonObject[TAG_SERVICEINFO].Get(); + } + if (!jsonObject[TAG_ACL_CHECKSUM].IsString()) { // Re-parse the acl + LOGE("ParseSyncMessage TAG_ACL_CHECKSUM error"); + return ERR_DM_FAILED; + } + std::string aclChecksumList = jsonObject[TAG_ACL_CHECKSUM].Get(); + return ParaseAclChecksumList(aclChecksumList, access); +} + +int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr &context, + DmAccess &access, std::string &enSyncMsg) +{ + std::string syncMsgCompress = ""; + int32_t ret = cryptoMgr_->DecryptMessage(enSyncMsg, syncMsgCompress); + if (ret != DM_OK) { + LOGE("DecryptSyncMessage syncMsg error"); + return ret; + } + JsonObject plainJson(syncMsgCompress); + if (plainJson.IsDiscarded()) { + LOGE("DecryptSyncMessage plainJson error"); + return ERR_DM_FAILED; + } + if (!plainJson[TAG_COMPRESS_ORI_LEN].IsNumberInteger()) { + LOGE("DecryptSyncMessage TAG_COMPRESS_ORI_LEN json error"); + return ERR_DM_FAILED; + } + int32_t dataLen = plainJson[TAG_COMPRESS_ORI_LEN].Get(); + if (!plainJson[TAG_COMPRESS].IsString()) { + LOGE("DecryptSyncMessage TAG_COMPRESS_ORI_LEN json error"); + return ERR_DM_FAILED; + } + std::string compressMsg = plainJson[TAG_COMPRESS].Get(); + std::string compressBase64 = Base64Decode(compressMsg); + std::string syncMsg = DecompressSyncMsg(compressBase64, dataLen); + JsonObject jsonObject(syncMsg); + if (jsonObject.IsDiscarded()) { + LOGE("DmAuthMessageProcessor::DecryptSyncMessage jsonStr error"); + return ERR_DM_FAILED; + } + + ret = ParseSyncMessage(context, access, jsonObject); + if (ret != DM_OK) { + LOGE("DecryptSyncMessage ParseSyncMessage jsonStr error"); + return ret; + } + return DM_OK; +} + +// Parse 180 message, save remote encrypted quadruple, acl, sp skid +int32_t DmAuthMessageProcessor::ParseMessageSyncReq(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (!jsonObject[TAG_SYNC].IsString()) { + LOGE("ParseMessageSyncReq json error"); + return ERR_DM_FAILED; + } + std::string enSyncMsg = jsonObject[TAG_SYNC].Get(); + // Decrypt data and parse data into context + int32_t ret = DecryptSyncMessage(context, context->accesser, enSyncMsg); + if (ret != DM_OK) { + LOGE("DecryptSyncMessage enSyncMsg error"); + return ret; + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +// Parse 190 message save the remote encrypted quadruple, acl sp skid +int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (!jsonObject[TAG_SYNC].IsString()) { + LOGE("ParseMessageSyncResp json error"); + return ERR_DM_FAILED; + } + std::string enSyncMsg = jsonObject[TAG_SYNC].Get(); + // Decrypt data and parse data into context + int32_t ret = DecryptSyncMessage(context, context->accessee, enSyncMsg); + if (ret != DM_OK) { + LOGE("DecryptSyncMessage enSyncMsg error"); + return ret; + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +// Parse 200 message +int32_t DmAuthMessageProcessor::ParseMessageSinkFinish(const JsonObject &jsonObject, + std::shared_ptr context) +{ + /* In case of an exception, there may be a state waiting for an event. + In the normal process, no state is waiting for events. */ + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + if (jsonObject[TAG_REPLY].IsNumberInteger()) { + context->reply = jsonObject[TAG_REPLY].Get(); + } + if (jsonObject[TAG_STATE].IsNumberInteger()) { + context->state = jsonObject[TAG_STATE].Get(); + } + if (jsonObject[TAG_REASON].IsNumberInteger()) { + context->reason = jsonObject[TAG_REASON].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +// Parse 201 message +int32_t DmAuthMessageProcessor::ParseMessageSrcFinish(const JsonObject &jsonObject, + std::shared_ptr context) +{ + /* In case of an exception, there may be a state waiting for an event. + In the normal process, no state is waiting for events. */ + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + if (jsonObject[TAG_REPLY].IsNumberInteger()) { + context->reply = jsonObject[TAG_REPLY].Get(); + } + if (jsonObject[TAG_STATE].IsNumberInteger()) { + context->state = jsonObject[TAG_STATE].Get(); + } + if (jsonObject[TAG_REASON].IsNumberInteger()) { + context->reason = jsonObject[TAG_REASON].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject[TAG_SESSION_NAME].IsString()) { + context->sessionName = jsonObject[TAG_SESSION_NAME].Get(); + } + + if (jsonObject[TAG_DMVERSION].IsString()) { + context->accesser.dmVersion = jsonObject[TAG_DMVERSION].Get(); + } + if (jsonObject[TAG_USER_ID].IsNumberInteger()) { + context->accesser.userId = jsonObject[TAG_USER_ID].Get(); + } + if (jsonObject[TAG_DEVICE_ID_HASH].IsString()) { + context->accesser.deviceIdHash = jsonObject[TAG_DEVICE_ID_HASH].Get(); + } + if (jsonObject[TAG_USER_ID_HASH].IsString()) { + context->accesser.userIdHash = jsonObject[TAG_USER_ID_HASH].Get(); + } + if (jsonObject[TAG_ACCOUNT_ID_HASH].IsString()) { + context->accesser.accountIdHash = jsonObject[TAG_ACCOUNT_ID_HASH].Get(); + } + if (jsonObject[TAG_TOKEN_ID_HASH].IsString()) { + context->accesser.tokenIdHash = jsonObject[TAG_TOKEN_ID_HASH].Get(); + } + if (jsonObject[TAG_BUNDLE_NAME].IsString()) { + context->accesser.bundleName = jsonObject[TAG_BUNDLE_NAME].Get(); + } + if (jsonObject[TAG_EXTRA_INFO].IsString()) { + context->accesser.extraInfo = jsonObject[TAG_EXTRA_INFO].Get(); + } + + if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { + context->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); + } + if (jsonObject[TAG_PEER_DISPLAY_ID].IsNumberInteger()) { + context->accessee.displayId = jsonObject[TAG_PEER_DISPLAY_ID].Get(); + } + + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject[TAG_DEVICE_VERSION].IsString()) { + context->accessee.dmVersion = jsonObject[TAG_DEVICE_VERSION].Get(); + } + + if (jsonObject[TAG_DEVICE_NAME].IsString()) { + context->accessee.deviceName = jsonObject[TAG_DEVICE_NAME].Get(); + } + + if (jsonObject[TAG_DEVICE_ID_HASH].IsString()) { + context->accessee.deviceIdHash = jsonObject[TAG_DEVICE_ID_HASH].Get(); + } + + if (jsonObject[TAG_USER_ID_HASH].IsString()) { + context->accessee.userIdHash = jsonObject[TAG_USER_ID_HASH].Get(); + } + + if (jsonObject[TAG_ACCOUNT_ID_HASH].IsString()) { + context->accessee.accountIdHash = jsonObject[TAG_ACCOUNT_ID_HASH].Get(); + } + + if (jsonObject[TAG_TOKEN_ID_HASH].IsString()) { + context->accessee.tokenIdHash = jsonObject[TAG_TOKEN_ID_HASH].Get(); + } + + if (jsonObject[TAG_IS_ONLINE].IsBoolean()) { + context->isOnline = jsonObject[TAG_IS_ONLINE].Get(); + } + + if (jsonObject[TAG_ACL_LIST].IsString()) { + context->accessee.aclList = jsonObject[TAG_ACL_LIST].Get(); + } + + if (jsonObject[TAG_CERT_TYPE_LIST].IsString()) { + context->accessee.credTypeList = jsonObject[TAG_CERT_TYPE_LIST].Get(); + } + + if (jsonObject[TAG_LANGUAGE].IsString()) { + context->accessee.language = jsonObject[TAG_LANGUAGE].Get(); + } + + if (jsonObject[TAG_EXTRA_INFO].IsString()) { + context->accessee.extraInfo = jsonObject[TAG_EXTRA_INFO].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const JsonObject &json, + std::shared_ptr context) +{ + if (json[TAG_DEVICE_TYPE].IsNumberInteger()) { + context->accesser.deviceType = json[TAG_DEVICE_TYPE].Get(); + } + if (json[TAG_DEVICE_NAME].IsString()) { + context->accesser.deviceName = json[TAG_DEVICE_NAME].Get(); + } + if (json[TAG_AUTH_TYPE].IsNumberInteger()) { + context->authType = static_cast(json[TAG_AUTH_TYPE].Get()); + } + if (json[TAG_ACL_LIST].IsString()) { + context->accesser.aclList = json[TAG_ACL_LIST].Get(); + } + if (json[TAG_CERT_TYPE_LIST].IsString()) { + context->accesser.credTypeList = json[TAG_CERT_TYPE_LIST].Get(); + } + if (json[TAG_EXTRA_INFO].IsString()) { + context->accesser.extraInfo = json[TAG_EXTRA_INFO].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const JsonObject &json, + std::shared_ptr context) +{ + if (json[TAG_AUTH_RESULT].IsNumberInteger()) { + context->authResult = static_cast(json[TAG_AUTH_RESULT].Get()); + } + + if (json[TAG_AUTH_TYPE_LIST].IsString()) { + auto strList = json[TAG_AUTH_TYPE_LIST].Get(); + context->authTypeList = stringToVectorAuthType(strList); + } + if (json[TAG_EXTRA_INFO].IsString()) { + context->accessee.extraInfo = json[TAG_EXTRA_INFO].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const JsonObject &json, + std::shared_ptr context) +{ + if (json[TAG_DATA].IsString()) { + context->transmitData = json[TAG_DATA].Get(); + } + + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthStart(const JsonObject &json, + std::shared_ptr context) +{ + if (json[TAG_DATA].IsString()) { + context->transmitData = json[TAG_DATA].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const JsonObject &json, + std::shared_ptr context) +{ + if (json[TAG_DATA].IsString()) { + context->transmitData = json[TAG_DATA].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json) +{ + json[TAG_AUTH_TYPE] = context->authType; + json[TAG_ACL_LIST] = context->accesser.aclList; + json[TAG_CERT_TYPE_LIST] = context->accesser.credTypeList; + json[TAG_DEVICE_TYPE] = context->accesser.deviceType; + json[TAG_DEVICE_NAME] = context->accesser.deviceName; + json[TAG_EXTRA_INFO] = context->accesser.extraInfo; + + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json) +{ + json[TAG_AUTH_RESULT] = context->authResult; + json[TAG_AUTH_TYPE_LIST] = vectorAuthTypeToString(context->authTypeList); + json[TAG_EXTRA_INFO] = context->accessee.extraInfo; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageReqPinAuthStart(std::shared_ptr context, JsonObject &json) +{ + json[TAG_DATA] = context->transmitData; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json) +{ + json[TAG_DATA] = context->transmitData; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate(std::shared_ptr context, + JsonObject &json) +{ + json[TAG_DATA] = context->transmitData; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate(std::shared_ptr context, + JsonObject &json) +{ + json[TAG_DATA] = context->transmitData; + return DM_OK; +} + +void DmAuthMessageProcessor::CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context) +{ + auto message = CreateMessage(msgType, context); + context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + +std::string DmAuthMessageProcessor::CompressSyncMsg(std::string &inputStr) +{ + uint32_t srcLen = inputStr.size(); + uint32_t boundSize = compressBound(srcLen); // Maximum compression length + std::string compressed(boundSize, '\0'); + + // Compress to reserved space + unsigned long destSize = boundSize; // Actual usable length + int32_t ret = compress(reinterpret_cast(&compressed[0]), &destSize, + reinterpret_cast(inputStr.data()), srcLen); + if (ret != Z_OK) { + LOGE("DmAuthMessageProcessor::CompressSyncMsg zlib compress failed"); + return ""; + } + compressed.resize(destSize); // Actual usage length + return compressed; +} + +std::string DmAuthMessageProcessor::DecompressSyncMsg(std::string& compressed, uint32_t oriLen) +{ + std::string decompressed; + decompressed.resize(oriLen); + unsigned long destLen = oriLen; // Actual usage length + int32_t ret = uncompress(reinterpret_cast(&decompressed[0]), &destLen, + reinterpret_cast(compressed.data()), // Skip header when decompressing + compressed.size()); + if (ret != Z_OK || destLen != oriLen) { + LOGE("DmAuthMessageProcessor::DecompressSyncMsg decompress failed"); + return ""; + } + return decompressed; +} + +std::string DmAuthMessageProcessor::Base64Encode(std::string &inputStr) +{ + // Convert input string to binary + const unsigned char* src = reinterpret_cast(inputStr.data()); + size_t srcLen = inputStr.size(); + + // Calculate the maximum length after base64 encoding + size_t maxEncodeLen = ((srcLen + 2) / 3) * 4 + 1; + std::vector buffer(maxEncodeLen); + + // Actual encoding length + size_t encodedLen = 0; + int32_t ret = mbedtls_base64_encode(buffer.data(), buffer.size(), &encodedLen, src, srcLen); + if (ret != 0) { + LOGE("DmAuthMessageProcessor::Base64Encode mbedtls_base64_encode failed"); + return ""; + } + return std::string(reinterpret_cast(buffer.data()), encodedLen); // No terminator needed +} + +std::string DmAuthMessageProcessor::Base64Decode(std::string &inputStr) +{ + // Convert input string to binary + const unsigned char* src = reinterpret_cast(inputStr.data()); + size_t srcLen = inputStr.size(); + + // Calculate the maximum length after base64 encoding + size_t maxEncodeLen = (srcLen / 4) * 3 + 1; + std::vector buffer(maxEncodeLen); + + // Actual encoding length + size_t decodedLen = 0; + int32_t ret = mbedtls_base64_decode(buffer.data(), buffer.size(), &decodedLen, src, srcLen); + if (ret != 0) { + LOGE("DmAuthMessageProcessor::Base64Decode mbedtls_base64_decode failed"); + return ""; + } + return std::string(reinterpret_cast(buffer.data()), decodedLen); // 无需终止符 +} + +int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr &context, DmAccess &accessSide, + std::string &encSyncMsg) +{ + JsonObject syncMsgJson; + DmAccessToSync accessToSync; + accessToSync.deviceName = accessSide.deviceName; + accessToSync.deviceId = accessSide.deviceId; + accessToSync.userId = accessSide.userId; + accessToSync.accountId = accessSide.accountId; + accessToSync.tokenId = accessSide.tokenId; + accessToSync.bundleName = accessSide.bundleName; + accessToSync.bindLevel = accessSide.bindLevel; + syncMsgJson[TAG_TRANSMIT_SK_ID] = std::to_string(accessSide.transmitSessionKeyId); + syncMsgJson[TAG_TRANSMIT_SK_TIMESTAMP] = std::to_string(accessSide.transmitSkTimeStamp); + syncMsgJson[TAG_TRANSMIT_CREDENTIAL_ID] = accessSide.transmitCredentialId; + if (!context->isOnline) { // First certification + syncMsgJson[TAG_LNN_SK_ID]=std::to_string(accessSide.lnnSessionKeyId); + syncMsgJson[TAG_LNN_SK_TIMESTAMP]=std::to_string(accessSide.lnnSkTimeStamp); + syncMsgJson[TAG_LNN_CREDENTIAL_ID] = accessSide.lnnCredentialId; + } + + JsonObject accessJsonObj{}; + accessJsonObj = accessToSync; + syncMsgJson[TAG_DMVERSION] = accessSide.dmVersion; + syncMsgJson[TAG_ACCESS] = accessJsonObj.Dump(); + syncMsgJson[TAG_PROXY] = ""; // Reserved field, leave blank + std::string aclHashList; + int32_t ret = GetAclListStr(context, aclHashList); + if (ret != DM_OK) { + LOGE("DmAuthMessageProcessor::EncryptSyncMessage GetAclListStr failed"); + return ERR_DM_FAILED; + } + + syncMsgJson[TAG_ACL_CHECKSUM] = aclHashList; + std::string syncMsg = syncMsgJson.Dump(); + + std::string compressMsg = CompressSyncMsg(syncMsg); + if (compressMsg.empty()) { + LOGE("DmAuthMessageProcessor::EncryptSyncMessage compress failed"); + return ERR_DM_FAILED; + } + JsonObject plainJson; + plainJson[TAG_COMPRESS_ORI_LEN] = syncMsg.size(); + plainJson[TAG_COMPRESS] = Base64Encode(compressMsg); + return cryptoMgr_->EncryptMessage(plainJson.Dump(), encSyncMsg); +} + +int32_t DmAuthMessageProcessor::ACLToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string aclStr) +{ + DmAccessControlTable dmAcl; + dmAcl.accessControlId = acl.GetAccessControlId(); + dmAcl.accesserId = acl.GetAccesserId(); + dmAcl.accesseeId = acl.GetAccesseeId(); + dmAcl.deviceId = acl.GetTrustDeviceId(); + dmAcl.sessionKey = acl.GetSessionKey(); + dmAcl.bindType = acl.GetBindType(); + dmAcl.authType = acl.GetAuthenticationType(); + dmAcl.deviceType = acl.GetDeviceIdType(); + dmAcl.deviceIdHash = acl.GetDeviceIdHash(); + dmAcl.status = acl.GetStatus(); + dmAcl.validPeriod = acl.GetValidPeriod(); + dmAcl.lastAuthTime = acl.GetLastAuthTime(); + dmAcl.bindLevel = acl.GetBindType(); + JsonObject aclJsonObj{}; + aclJsonObj = dmAcl; + aclStr = aclJsonObj.Dump(); + if (aclStr.empty()) { + LOGE("DmAuthMessageProcessor::ACLToStr normalized acl failed"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +std::string DmAuthMessageProcessor::AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl) +{ + JsonObject jsonAccesserObj; + DistributedDeviceProfile::Accesser accesser = acl.GetAccesser(); + jsonAccesserObj[TAG_ACCESSER_DEVICE_ID] = accesser.GetAccesserDeviceId(); + jsonAccesserObj[TAG_ACCESSER_USER_ID] = accesser.GetAccesserUserId(); + jsonAccesserObj[TAG_ACCESSER_ACOUNT_ID] = accesser.GetAccesserAccountId(); + jsonAccesserObj[TAG_ACCESSER_TOKEN_ID] = accesser.GetAccesserTokenId(); + jsonAccesserObj[TAG_ACCESSER_SERVICE_NAME] = std::vector(); // Reserved field + jsonAccesserObj[TAG_ACCESSER_BUNDLE_NAME] = accesser.GetAccesserBundleName(); + jsonAccesserObj[TAG_ACCESSER_HAP_SIGNATURE] = accesser.GetAccesserHapSignature(); + jsonAccesserObj[TAG_ACCESSER_BIND_LEVEL] = accesser.GetAccesserBindLevel(); + jsonAccesserObj[TAG_ACCESSER_CREDENTIAL_ID] = accesser.GetAccesserBindLevel(); + jsonAccesserObj[TAG_ACCESSER_STATUS] = accesser.GetAccesserStatus(); + jsonAccesserObj[TAG_ACCESSER_SK_ID] = accesser.GetAccesserSessionKeyId(); + jsonAccesserObj[TAG_ACCESSER_SK_TIMESTAMP] = accesser.GetAccesserSKTimeStamp(); + return jsonAccesserObj.Dump(); +} + +std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::AccessControlProfile acl) +{ + JsonObject jsonAccesseeObj; + DistributedDeviceProfile::Accessee accessee = acl.GetAccessee(); + jsonAccesseeObj[TAG_ACCESSEE_DEVICE_ID] = accessee.GetAccesseeDeviceId(); + jsonAccesseeObj[TAG_ACCESSEE_USER_ID] = accessee.GetAccesseeUserId(); + jsonAccesseeObj[TAG_ACCESSEE_ACOUNT_ID] = accessee.GetAccesseeAccountId(); + jsonAccesseeObj[TAG_ACCESSEE_TOKEN_ID] = accessee.GetAccesseeTokenId(); + jsonAccesseeObj[TAG_ACCESSEE_SERVICE_NAME] = std::vector(); // Reserved field + jsonAccesseeObj[TAG_ACCESSEE_BUNDLE_NAME] = accessee.GetAccesseeBundleName(); + jsonAccesseeObj[TAG_ACCESSEE_HAP_SIGNATURE] = accessee.GetAccesseeHapSignature(); + jsonAccesseeObj[TAG_ACCESSEE_BIND_LEVEL] = accessee.GetAccesseeBindLevel(); + jsonAccesseeObj[TAG_ACCESSEE_CREDENTIAL_ID] = accessee.GetAccesseeBindLevel(); + jsonAccesseeObj[TAG_ACCESSEE_STATUS] = accessee.GetAccesseeStatus(); + jsonAccesseeObj[TAG_ACCESSEE_SK_ID] = accessee.GetAccesseeSessionKeyId(); + jsonAccesseeObj[TAG_ACCESSEE_SK_TIMESTAMP] = accessee.GetAccesseeSKTimeStamp(); + return jsonAccesseeObj.Dump(); +} + +int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr context, JsonObject &jsonObject) +{ + DmAccess accessSide; + if (context->direction == DM_AUTH_SOURCE) { + accessSide = context->accesser; + } else { + accessSide = context->accessee; + } + std::string encSyncMsg; + int32_t ret = EncryptSyncMessage(context, accessSide, encSyncMsg); + if (ret != DM_OK) { + LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); + return ret; + } + jsonObject[TAG_SYNC] = encSyncMsg; + return DM_OK; +} + +int32_t DmAuthMessageProcessor::ParseAuthStartMessage(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject.IsDiscarded() || !jsonObject.Contains(TAG_DATA) || + !jsonObject[TAG_DATA].IsString()) { + LOGE("DmAuthMessageProcessor::ParseAuthStartMessage Unlegal json string failed"); + return ERR_DM_FAILED; + } + context->transmitData = jsonObject[TAG_DATA].Get(); + + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &context, std::string &aclList) +{ + JsonObject jsonAclListObj; + jsonAclListObj[TAG_DMVERSION] = context->accesser.dmVersion; + + // Query ACL. + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + std::vector accceserStrList; + std::vector accceseeStrList; + // Traverse the ACL table to find historical ACL records at both ends. + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && + item.GetAccesser().GetAccesserUserId() == context->accesser.userId && + item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && + item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { + // Save the digest using SHA256. + uint8_t accesserHash[DM_HASH_LEN] = {0}; + std::string accesserStr = AccesserToStr(item); + Crypto::DmGenerateStrHash(accesserStr.data(), accesserStr.size(), accesserHash, DM_HASH_LEN, 0); + accceserStrList.push_back(reinterpret_cast(accesserHash)); + + uint8_t accesseeHash[DM_HASH_LEN] = {0}; + std::string accesseeStr = AccesseeToStr(item); + Crypto::DmGenerateStrHash(accesseeStr.data(), accesseeStr.size(), accesseeHash, DM_HASH_LEN, 0); + accceseeStrList.push_back(reinterpret_cast(accesseeHash)); + } + } + if (accceserStrList.empty() || accceseeStrList.empty()) { + LOGI("DmAuthMessageProcessor::CreateSyncMessage acl lis is empty"); + } + + jsonAclListObj[TAG_ACCESSER] = accceserStrList; + jsonAclListObj[TAG_ACCESSEE] = accceseeStrList; + aclList = jsonAclListObj.Dump(); + return DM_OK; +} + +void ToJson(JsonItemObject &itemObject, const DmAccessControlTable &table) +{ + itemObject["accessControlId"] = table.accessControlId; + itemObject["accesserId"] = table.accesserId; + itemObject["accesseeId"] = table.accesseeId; + itemObject["deviceId"] = table.deviceId; + itemObject["sessionKey"] = table.sessionKey; + itemObject["bindType"] = table.bindType; + itemObject["authType"] = table.authType; + itemObject["deviceType"] = table.deviceType; + itemObject["deviceIdHash"] = table.deviceIdHash; + itemObject["status"] = table.status; + itemObject["validPeriod"] = table.validPeriod; + itemObject["lastAuthTime"] = table.lastAuthTime; + itemObject["bindLevel"] = table.bindLevel; +} + +void FromJson(const JsonItemObject &itemObject, DmAccessControlTable &table) +{ + SetValueFromJson(itemObject, "accessControlId", &JsonItemObject::IsNumberInteger, table.accessControlId); + SetValueFromJson(itemObject, "accesserId", &JsonItemObject::IsNumberInteger, table.accesserId); + SetValueFromJson(itemObject, "accesseeId", &JsonItemObject::IsNumberInteger, table.accesseeId); + SetValueFromJson(itemObject, "deviceId", &JsonItemObject::IsNumberInteger, table.deviceId); + SetValueFromJson(itemObject, "sessionKey", &JsonItemObject::IsString, table.sessionKey); + SetValueFromJson(itemObject, "bindType", &JsonItemObject::IsNumberInteger, table.bindType); + SetValueFromJson(itemObject, "authType", &JsonItemObject::IsNumberInteger, table.authType); + SetValueFromJson(itemObject, "deviceType", &JsonItemObject::IsNumberInteger, table.deviceType); + SetValueFromJson(itemObject, "deviceIdHash", &JsonItemObject::IsString, table.deviceIdHash); + SetValueFromJson(itemObject, "status", &JsonItemObject::IsNumberInteger, table.status); + SetValueFromJson(itemObject, "validPeriod", &JsonItemObject::IsNumberInteger, table.validPeriod); + SetValueFromJson(itemObject, "lastAuthTime", &JsonItemObject::IsNumberInteger, table.lastAuthTime); + SetValueFromJson(itemObject, "bindLevel", &JsonItemObject::IsNumberInteger, table.bindLevel); +} + +void ToJson(JsonItemObject &itemObject, const DmAccessToSync &table) +{ + itemObject["deviceName"] = table.deviceName; + itemObject["deviceId"] = table.deviceId; + itemObject["userId"] = table.userId; + itemObject["accountId"] = table.accountId; + itemObject["tokenId"] = table.tokenId; + itemObject["bundleName"] = table.bundleName; + itemObject["bindLevel"] = table.bindLevel; + itemObject["sessionKeyId"] = table.sessionKeyId; + itemObject["skTimeStamp"] = table.skTimeStamp; +} + +void FromJson(const JsonItemObject &itemObject, DmAccessToSync &table) +{ + SetValueFromJson(itemObject, "deviceName", &JsonItemObject::IsString, table.deviceName); + SetValueFromJson(itemObject, "deviceId", &JsonItemObject::IsString, table.deviceId); + SetValueFromJson(itemObject, "userId", &JsonItemObject::IsNumberInteger, table.userId); + SetValueFromJson(itemObject, "accountId", &JsonItemObject::IsString, table.accountId); + SetValueFromJson(itemObject, "tokenId", &JsonItemObject::IsNumberInteger, table.tokenId); + SetValueFromJson(itemObject, "bundleName", &JsonItemObject::IsString, table.bundleName); + SetValueFromJson(itemObject, "bindLevel", &JsonItemObject::IsNumberInteger, table.bindLevel); + SetValueFromJson(itemObject, "sessionKeyId", &JsonItemObject::IsNumberInteger, table.sessionKeyId); + SetValueFromJson(itemObject, "skTimeStamp", &JsonItemObject::IsNumberInteger, table.skTimeStamp); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp new file mode 100644 index 000000000..b8006dd2b --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -0,0 +1,296 @@ +/* + * Copyright (c) 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 "access_control_profile.h" +#include "hichain_auth_connector.h" +#include "multiple_user_connector.h" +#include "dm_crypto.h" +#include "dm_auth_state.h" +#include "dm_auth_context.h" +#include "dm_auth_manager_base.h" +#include "dm_auth_state_machine.h" +#include "dm_crypto.h" +#include "dm_softbus_cache.h" +#if defined(SUPPORT_SCREENLOCK) +#include "screenlock_manager.h" +#endif +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +// clone task timeout map +const std::map TASK_TIME_OUT_MAP = { + { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, + { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT }, + { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT }, + { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT }, + { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT }, + { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, + { std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), CLONE_PIN_AUTH_TIMEOUT }, + { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } +}; + +int32_t DmAuthState::GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut) +{ + LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, context->authType); + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { + auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); + if (timeout != TASK_TIME_OUT_MAP.end()) { + return timeout->second; + } + } + return taskTimeOut; +} + +void DmAuthState::HandleAuthenticateTimeout(std::shared_ptr context, std::string name) +{ + LOGI("DmAuthContext::HandleAuthenticateTimeout start timer name %{public}s", name.c_str()); + context->timer->DeleteTimer(name); + context->reason = ERR_DM_TIME_OUT; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + LOGI("DmAuthContext::HandleAuthenticateTimeout complete"); +} + +bool DmAuthState::IsScreenLocked() +{ + bool isLocked = false; +#if defined(SUPPORT_SCREENLOCK) + isLocked = OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked(); +#endif + LOGI("IsScreenLocked isLocked: %{public}d.", isLocked); + return isLocked; +} + +void DmAuthState::SyncAclList(std::shared_ptr context, int32_t userId, + std::string credId, int32_t sessionKeyId, int32_t aclId) +{ + LOGI("SyncAclList userId:%{public}d, credId:%{public}s, sessionKeyId:%{public}d, aclId:%{public}d", + userId, credId.c_str(), sessionKeyId, aclId); + // 根据凭据id 删除sink端多余的凭据 + int32_t ret = context->hiChainAuthConnector->DeleteCredential(userId, credId); + if (ret != DM_OK) { + LOGE("SyncAclList DeleteCredential failed."); + } + // 根据skid删除sk,删除skid + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(sessionKeyId); + if (ret != DM_OK) { + LOGE("SyncAclList DeleteSessionKey failed."); + } + // 删除本条acl + DeviceProfileConnector::GetInstance().DeleteAccessControlById(aclId); +} + +void DmAuthState::SourceFinish(std::shared_ptr context) +{ + LOGI("SourceFinish reason:%{public}d", context->reason); + context->listener->OnAuthResult(context->processInfo, context->peerTargetId.deviceId, context->accessee.tokenIdHash, + context->state, context->reason); + context->listener->OnBindResult(context->processInfo, context->peerTargetId, context->reply, + context->state, GenerateBindResultContent(context->accessee)); + context->isFinished = true; + + if (context->reason != DM_OK && context->reason != DM_ALREADY_AUTHED) { + // 根据凭据id 删除sink端多余的凭据 + context->hiChainAuthConnector->DeleteCredential(context->accesser.userId, + context->accesser.lnnCredentialId); + context->hiChainAuthConnector->DeleteCredential(context->accesser.userId, + context->accesser.transmitCredentialId); + // 根据skid删除sk,删除skid + DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.lnnSessionKeyId); + DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.transmitSessionKeyId); + } + LOGI("SourceFinish notify online"); + if (SoftbusCache::GetInstance().CheckIsOnline(context->accessee.deviceId)) { + context->softbusConnector->HandleDeviceOnline(context->accessee.deviceId, context->GetBindType()); + } + + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); + context->authStateMachine->Stop(); + context->timer->DeleteAll(); +} + +void DmAuthState::SinkFinish(std::shared_ptr context) +{ + LOGI("SinkFinish reason:%{public}d", context->reason); + context->listener->OnSinkBindResult(context->processInfo, context->peerTargetId, context->reply, + context->state, GenerateBindResultContent(context->accesser)); + context->isFinished = true; + if (context->reason != DM_OK) { + // 根据凭据id 删除sink端多余的凭据 + context->hiChainAuthConnector->DeleteCredential(context->accessee.userId, + context->accessee.lnnCredentialId); + context->hiChainAuthConnector->DeleteCredential(context->accessee.userId, + context->accessee.transmitCredentialId); + // 根据skid删除sk,删除skid + DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.lnnSessionKeyId); + DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.transmitSessionKeyId); + } else { + SetAclInfo(context); + context->authMessageProcessor->PutAccessControlList(context, context->accessee, context->accesser.deviceId); + LOGI("SinkFinish notify online"); + if (SoftbusCache::GetInstance().CheckIsOnline(context->accesser.deviceId)) { + context->softbusConnector->HandleDeviceOnline(context->accesser.deviceId, context->GetBindType()); + } + } + + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); + context->authStateMachine->Stop(); + context->timer->DeleteAll(); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_RESP_FINISH, context); // 发送201给source侧 +} + +std::string DmAuthState::GenerateBindResultContent(DmAccess &access) +{ + JsonObject jsonObj; + jsonObj[DM_BIND_RESULT_NETWORK_ID] = access.networkId; + if (access.deviceId.empty()) { + jsonObj[TAG_DEVICE_ID] = ""; + } else { + char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + Crypto::GetUdidHash(access.deviceId, reinterpret_cast(deviceIdHash)); + jsonObj[TAG_DEVICE_ID] = deviceIdHash; + } + std::string content = jsonObj.Dump(); + return content; +} + +bool DmAuthState::NeedReqUserConfirm(std::shared_ptr context) +{ + // 不管是否有可信关系,都需要走pin码认证,主要指鸿蒙环PIN码导入场景 + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { + return true; + } + + // 有ACL,跳转到结束状态,发200报文,直接组网 + DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + if (access.isAuthed) { + return false; + } + + return true; +} + +bool DmAuthState::NeedAgreeCredential(std::shared_ptr context) +{ + return context->needAgreeCredential; +} + +bool DmAuthState::NeedAgreeAcl(std::shared_ptr context) +{ + return (context->direction == DM_AUTH_SOURCE) ? !context->accesser.isAuthed : !context->accessee.isAuthed; +} + +bool DmAuthState::IsImportAuthCodeCompatibility(DmAuthType authType) +{ + if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE || + authType == DmAuthType::AUTH_TYPE_NFC) { + return true; + } + return false; +} + +bool DmAuthState::IsQuadrupleAndBindLevelSame(std::shared_ptr context) +{ + const DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accessee : context->accesser; + bool isSame = Crypto::Sha256(access.deviceId) == access.deviceIdHash && + Crypto::Sha256(std::to_string(access.userId)) == access.userIdHash && + Crypto::Sha256(access.accountId) == access.accountIdHash && + Crypto::Sha256(std::to_string(access.tokenId)) == access.tokenIdHash && + context->accesser.bindLevel == context->accessee.bindLevel; + if (!isSame) { + context->reason = ERR_DM_QUADRUPLE_NOT_SAME; + context->reply = ERR_DM_QUADRUPLE_NOT_SAME; + context->state = static_cast(GetStateType()); + if (context->direction == DM_AUTH_SOURCE) { + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_REQ_FINISH, context); + } else { + context->authStateMachine->TransitionTo(std::make_shared()); + } + } + + return isSame; +} + +std::vector DmAuthState::GetAclList(std::shared_ptr + context) +{ + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + std::vector aclList; + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && + item.GetAccesser().GetAccesserUserId() == context->accesser.userId && + item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && + item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { + aclList.push_back(item); + } + } + + if (aclList.empty()) { + LOGI("DmAuthState::GetAclList acl is empty"); + } + + return aclList; +} + +void DmAuthState::SetAclExtraInfo(std::shared_ptr context) +{ + DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; + DmAccess &remoteAccess = (context->direction == DM_AUTH_SOURCE) ? context->accessee : context->accesser; + JsonObject jsonObj; + jsonObj[TAG_DMVERSION] = access.dmVersion; + access.extraInfo = jsonObj.Dump(); + remoteAccess.extraInfo = jsonObj.Dump(); +} + +void DmAuthState::SetAclInfo(std::shared_ptr context) +{ + DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; + DmAccess &remoteAccess = (context->direction == DM_AUTH_SOURCE) ? context->accessee : context->accesser; + SetAclExtraInfo(context); + access.lnnBindType = GetAclBindType(context, access.lnnCredentialId); + remoteAccess.lnnBindType = GetAclBindType(context, remoteAccess.lnnCredentialId); + + access.transmitBindType = GetAclBindType(context, access.transmitCredentialId); + remoteAccess.transmitBindType = GetAclBindType(context, remoteAccess.transmitCredentialId); +} + +int32_t DmAuthState::GetAclBindType(std::shared_ptr context, std::string credId) +{ + DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accesser : context->accessee; + JsonObject result; + int32_t ret = context->hiChainAuthConnector->QueryCredInfoByCredId(access.userId, credId, result); + if (ret != DM_OK) { + LOGE("GetAclBindType QueryCredInfoByCredId failed, ret: %{public}d.", ret); + return DM_UNKNOWN_TYPE; + } + if (!result.Contains(credId)) { + LOGE("GetAclBindType result not contains credId."); + return DM_UNKNOWN_TYPE; + } + int32_t credType = result[credId][FILED_CRED_TYPE].Get(); + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED) { + return DM_SAME_ACCOUNT_TYPE; + } + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED) { + return DM_POINT_TO_POINT_TYPE; + } + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS) { + return DM_SHARE_TYPE; + } + return DM_UNKNOWN_TYPE; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp new file mode 100644 index 000000000..b384cf749 --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -0,0 +1,345 @@ +/* + * Copyright (c) 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 "dm_log.h" +#include "dm_constants.h" +#include "dm_auth_state.h" +#include "dm_auth_context.h" +#include "dm_auth_manager_base.h" +#include "dm_auth_state_machine.h" + +namespace OHOS { +namespace DistributedHardware { + +DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) +{ + exceptionEvent_= { + DmEventType::ON_ERROR, // Authentication error, there is a possibility of retry. + DmEventType::ON_TIMEOUT, + DmEventType::ON_FAIL, // Authentication failed + DmEventType::ON_SCREEN_LOCKED, + }; + + running_ = true; + direction_ = context->direction; + + if (direction_ == DM_AUTH_SOURCE) { + this->InsertSrcTransTable(); + } else { + this->InsertSinkTransTable(); + } + + this->SetCurState(DmAuthStateType::AUTH_IDLE_STATE); + thread_ = std::thread(&DmAuthStateMachine::Run, this, context); +} + +DmAuthStateMachine::~DmAuthStateMachine() +{ + Stop(); + thread_.join(); +} + +void DmAuthStateMachine::InsertSrcTransTable() +{ + // Source-end state transition table + stateTransitionTable_.insert({ + {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_START_STATE}}, + {DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, + {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, { + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, { + DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, + DmAuthStateType::AUTH_SRC_PIN_INPUT_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_INPUT_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, { + DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, { + DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, + DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, + }}, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, + + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE}}, + + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, + {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, + + {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SRC_FINISH_STATE}}, + + {DmAuthStateType::AUTH_SRC_FINISH_STATE, {}} + }); + + return; +} + +void DmAuthStateMachine::InsertSinkTransTable() +{ + // Sink-end state transition table + stateTransitionTable_.insert({ + {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, { + DmAuthStateType::AUTH_SINK_CONFIRM_STATE, + }}, + {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, { + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, { + DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE, + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, { + DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, + DmAuthStateType::AUTH_SINK_FINISH_STATE, + }}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, { + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, { + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, + }}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, + {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, + + {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SINK_FINISH_STATE}}, + {DmAuthStateType::AUTH_SINK_FINISH_STATE, {}} + }); + + return; +} + +// Notification status transition. The execution status corresponds to specific actions and exception handling. +int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) +{ + int32_t ret = DM_OK; + DmAuthStateType nextState = state->GetStateType(); + { + std::lock_guard lock(stateMutex_); + if (this->CheckStateTransitValid(nextState)) { + LOGI("DmAuthStateMachine: The state transition from %{public}d to %{public}d.", + statesQueue_.empty() ? GetCurState() : statesQueue_.back()->GetStateType(), nextState); + statesQueue_.push(state); + } else { + // The state transition is invalid. + LOGE("DmAuthStateMachine: The state transition does not meet the rule from %{public}d to %{public}d.", + statesQueue_.empty() ? GetCurState() : statesQueue_.back()->GetStateType(), nextState); + ret = ERR_DM_NEXT_STATE_INVALID; + reason = ERR_DM_NEXT_STATE_INVALID; + if (direction_ == DM_AUTH_SOURCE) { + statesQueue_.push(std::make_shared()); + } else { + statesQueue_.push(std::make_shared()); + } + } + } + stateCv_.notify_one(); + return ret; +} + +/* +Expected event in an action, which is used for blocking. +When the expected event is complete or other exceptions occur, the actual event is returned. +Other normal events continue to be blocked (only in the action). +*/ +DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) +{ + /* + 1. Actual event = Expected event, return actual event + 2. Actual event = Abnormal event (event timeout). The actual event is also returned. + 3. Actual event = Other events, continue to block, but there is a timeout limit. + */ + std::unique_lock lock(eventMutex_); + auto startTime = std::chrono::high_resolution_clock::now(); + while (running_.load()) { + eventCv_.wait(lock, [&] { + return !running_.load() || !eventQueue_.empty(); + }); + if (!running_.load()) { + return DmEventType::ON_FAIL; + } + + DmEventType actualEventType = eventQueue_.front(); + eventQueue_.pop(); + // Determine whether the event is an expected event or abnormal event in list. + if (actualEventType == eventType || (exceptionEvent_.find(actualEventType) != exceptionEvent_.end())) { + return actualEventType; + } + // Event Wait Timeout + auto elapsedTime = std::chrono::duration_cast( + std::chrono::high_resolution_clock::now() - startTime); + if (elapsedTime.count() >= EVENT_TIMEOUT) { + break; + } + } + return DmEventType::ON_TIMEOUT; +} + +/* +The event is invoked after the event is complete. +The event enumeration can be invoked only when the event is triggered. +If the event is an abnormal event, the reason or reply of the context must be recorded. +*/ +void DmAuthStateMachine::NotifyEventFinish(DmEventType eventType) +{ + LOGI("DmAuthStateMachine: NotifyEventFinish Event:%{public}d.", eventType); + { + std::unique_lock lock(eventMutex_); + eventQueue_.push(eventType); + } + eventCv_.notify_one(); + if (eventType == DmEventType::ON_FAIL) { + if (direction_ == DM_AUTH_SOURCE) { + this->TransitionTo(std::make_shared()); + } else { + this->TransitionTo(std::make_shared()); + } + } +} + +// Cyclically wait for state transition and execute action. +void DmAuthStateMachine::Run(std::shared_ptr context) +{ + while (running_.load()) { + auto state = FetchAndSetCurState(); + if (!state.has_value()) { + break; + } + if (reason != DM_OK) { + context->reason = reason; + } + // Obtain the status and execute the status action. + DmAuthStateType stateType = state.value()->GetStateType(); + int32_t ret = state.value()->Action(context); + if (ret != DM_OK) { + LOGE("DmAuthStateMachine::Run err:%{public}d", ret); + if (context->reason == DM_OK) { + // If the reason of the context is not set, set this parameter to ret. + context->reason = ret; + } + if (context->direction == DM_AUTH_SOURCE) { + this->TransitionTo(std::make_shared()); + } else { + this->TransitionTo(std::make_shared()); + } + } else { + LOGI("DmAuthStateMachine::Run ok state:%{public}d", stateType); + } + } + LOGI("DmAuthStateMachine::Run end"); +} + +std::optional> DmAuthStateMachine::FetchAndSetCurState() +{ + std::unique_lock lock(stateMutex_); + stateCv_.wait(lock, [&] { + return !running_.load() || !statesQueue_.empty(); + }); + + if (!running_.load()) return std::nullopt; + + std::shared_ptr state = statesQueue_.front(); + statesQueue_.pop(); + SetCurState(state->GetStateType()); + return state; +} + +void DmAuthStateMachine::Stop() +{ + running_.store(false); + stateCv_.notify_all(); + eventCv_.notify_all(); +} + +void DmAuthStateMachine::SetCurState(DmAuthStateType state) +{ + LOGI("DmAuthStateMachine::SetCurState state: %{public}d", state); + curState_ = state; +} + +DmAuthStateType DmAuthStateMachine::GetCurState() +{ + return curState_; +} + +// Verify the validity of the next state transition. +bool DmAuthStateMachine::CheckStateTransitValid(DmAuthStateType nextState) +{ + if (curState_ == nextState || curState_ == DmAuthStateType::AUTH_SRC_FINISH_STATE || + curState_ == DmAuthStateType::AUTH_SINK_FINISH_STATE) { + return false; + } + + /* + Check whether the next state is AuthSrcFinishState or AuthSinkFinishState + which can directly switch to the state and return. + */ + if (nextState == DmAuthStateType::AUTH_SRC_FINISH_STATE || nextState == DmAuthStateType::AUTH_SINK_FINISH_STATE) { + return true; + } + // Check whether the state transition table is met. + DmAuthStateType state = curState_; + if (!statesQueue_.empty()) { + state = statesQueue_.back()->GetStateType(); + } + auto it = stateTransitionTable_.find(state); + if (it != stateTransitionTable_.end()) { + const std::set& allowedStates = it->second; + return allowedStates.find(nextState) != allowedStates.end(); + } + return false; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/implementation/src/authentication_v2/dm_negotiate_process.cpp b/services/implementation/src/authentication_v2/dm_negotiate_process.cpp new file mode 100644 index 000000000..fc0d8bec7 --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_negotiate_process.cpp @@ -0,0 +1,285 @@ +/* + * Copyright (c) 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 "dm_negotiate_process.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(NegotiateProcess); + +int32_t OnlyPinBind(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + context->needBind = true; + context->needAgreeCredential = false; + context->needAuth = false; + return DM_OK; +} + +int32_t EndBind(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + context->needBind = false; + context->needAgreeCredential = false; + context->needAuth = false; + context->reason = ERR_DM_BIND_TRUST_TARGET; + return ERR_DM_BIND_TRUST_TARGET; +} + +int32_t OnlyCredAuth(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + context->needBind = false; + context->needAgreeCredential = false; + context->needAuth = true; + return DM_OK; +} + +int32_t PinBindAndCredAuth(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + context->needBind = true; + context->needAgreeCredential = true; + context->needAuth = true; + return DM_OK; +} + +NegotiateProcess::NegotiateProcess() +{ + LOGI("start."); + handlers_[NegotiateSpec(CredType::DM_NO_CRED, AclType::DM_NO_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_NO_CRED, AclType::DM_NO_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_IDENTICAL_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_IDENTICAL_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_IDENTICAL_CREDTYPE, AclType::DM_IDENTICAL_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_IDENTICAL_CREDTYPE, AclType::DM_IDENTICAL_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_IDENTICAL_CREDTYPE, AclType::DM_P2P_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_IDENTICAL_CREDTYPE, AclType::DM_P2P_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_SHARE_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_SHARE_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_P2P_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_SHARE_CREDTYPE, AclType::DM_P2P_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_P2P_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_P2P_CREDTYPE, AclType::DM_NO_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_P2P_CREDTYPE, AclType::DM_P2P_ACL, AuthType::DM_INPUT_PINCODE)] = + std::make_unique(); + handlers_[NegotiateSpec(CredType::DM_P2P_CREDTYPE, AclType::DM_P2P_ACL, AuthType::DM_IMPORT_AUTHTYPE)] = + std::make_unique(); +} + +int32_t NegotiateProcess::HandleNegotiateResult(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + CredType credType = ConvertCredType(context->accesser.credTypeList); + AclType aclType = ConvertAclType(context->accesser.aclList); + AuthType authType = ConvertAuthType(context->authType); + LOGI("credType %{public}d, aclType %{public}d, authType %{public}d.", + static_cast(credType), static_cast(aclType), static_cast(authType)); + NegotiateSpec negotiateSpec(credType, aclType, authType); + auto handler = handlers_.find(negotiateSpec); + if (handler != handlers_.end()) { + return handler->second->NegotiateHandle(context); + } + return ERR_DM_CAPABILITY_NEGOTIATE_FAILED; +} + +CredType NegotiateProcess::ConvertCredType(const std::string &credType) +{ + LOGI("start credType %{public}s.", credType.c_str()); + CredType credTypeTemp = CredType::DM_NO_CRED; + if (credType.empty()) { + return credTypeTemp; + } + JsonObject credTypeJson; + credTypeJson.Parse(credType); + if (credTypeJson.IsDiscarded()) { + LOGE("Parse credType str failed."); + return credTypeTemp; + } + if (credTypeJson.Contains("identicalCredType")) { + credTypeTemp = CredType::DM_IDENTICAL_CREDTYPE; + } else if (credTypeJson.Contains("shareCredType")) { + credTypeTemp = CredType::DM_SHARE_CREDTYPE; + } else if (credTypeJson.Contains("pointTopointCredType")) { + credTypeTemp = CredType::DM_P2P_CREDTYPE; + } else { + credTypeTemp = CredType::DM_NO_CRED; + } + return credTypeTemp; +} + +AclType NegotiateProcess::ConvertAclType(const std::string &aclType) +{ + LOGI("start credType %{public}s.", aclType.c_str()); + AclType aclTypeTemp = AclType::DM_NO_ACL; + if (aclType.empty()) { + return aclTypeTemp; + } + JsonObject aclTypeJson; + aclTypeJson.Parse(aclType); + if (aclTypeJson.IsDiscarded()) { + LOGE("Parse credType str failed."); + return aclTypeTemp; + } + if (aclTypeJson.Contains("identicalAcl")) { + aclTypeTemp = AclType::DM_IDENTICAL_ACL; + } else if (aclTypeJson.Contains("shareAcl")) { + aclTypeTemp = AclType::DM_SHARE_ACL; + } else if (aclTypeJson.Contains("pointTopointAcl")) { + aclTypeTemp = AclType::DM_P2P_ACL; + } else { + aclTypeTemp = AclType::DM_NO_ACL; + } + return aclTypeTemp; +} + +AuthType NegotiateProcess::ConvertAuthType(const DmAuthType &authType) +{ + LOGI("start authType %{public}d.", static_cast(authType)); + AuthType authTypeTemp = AuthType::DM_INVALIED_AUTHTYPE; + if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE || authType == DmAuthType::AUTH_TYPE_NFC) { + authTypeTemp = AuthType::DM_IMPORT_AUTHTYPE; + } else { + authTypeTemp = AuthType::DM_INPUT_PINCODE; + } + return authTypeTemp; +} + +int32_t NoCredNoAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return PinBindAndCredAuth(context); +} + +int32_t NoCredNoAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return PinBindAndCredAuth(context); +} + +int32_t IdentCredNoAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyCredAuth(context); +} + +int32_t IdentCredNoAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return PinBindAndCredAuth(context); +} + +int32_t IdentCredIdentAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return EndBind(context); +} + +int32_t IdentCredIdentAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyPinBind(context); +} + +int32_t IdentCredP2pAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyCredAuth(context); +} + +int32_t IdentCredP2pAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyPinBind(context); +} + +int32_t ShareCredNoAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyCredAuth(context); +} + +int32_t ShareCredNoAclImputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return PinBindAndCredAuth(context); +} + +int32_t ShareCredShareAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return EndBind(context); +} + +int32_t ShareCredShareAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyPinBind(context); +} + +int32_t ShareCredP2pAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyCredAuth(context); +} + +int32_t ShareCredP2pAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyPinBind(context); +} + +int32_t P2pCredNoAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return PinBindAndCredAuth(context); +} + +int32_t P2pCredNoAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return PinBindAndCredAuth(context); +} + +int32_t P2pCredP2pAclInputAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return EndBind(context); +} + +int32_t P2pCredP2pAclImportAuthType::NegotiateHandle(std::shared_ptr context) +{ + CHECK_NULL_RETURN(context, ERR_DM_POINT_NULL); + return OnlyPinBind(context); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/cryptomgr/crypto_mgr.cpp b/services/implementation/src/cryptomgr/crypto_mgr.cpp index 91d35dee0..4af9f65f9 100644 --- a/services/implementation/src/cryptomgr/crypto_mgr.cpp +++ b/services/implementation/src/cryptomgr/crypto_mgr.cpp @@ -17,6 +17,7 @@ #include #include +#include #include "mbedtls/base64.h" #include "mbedtls/cipher.h" @@ -308,6 +309,12 @@ int32_t CryptoMgr::SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyL return DM_OK; } +std::vector CryptoMgr::GetSessionKey() +{ + std::lock_guard lock(sessionKeyMtx_); + return std::vector(sessionKey_.key, sessionKey_.key + sessionKey_.keyLen); +} + void CryptoMgr::ClearSessionKey() { std::lock_guard lock(sessionKeyMtx_); diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 4ce5f2eb6..51343a786 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -12,6 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +#include #include "hichain_auth_connector.h" #include "dm_log.h" @@ -25,6 +27,7 @@ namespace OHOS { namespace DistributedHardware { std::shared_ptr HiChainAuthConnector::dmDeviceAuthCallback_ = nullptr; +std::map> HiChainAuthConnector::dmDeviceAuthCallbackMap_; std::mutex HiChainAuthConnector::dmDeviceAuthCallbackMutex_; void HiChainAuthConnector::FreeJsonString(char *jsonStr) @@ -47,6 +50,11 @@ HiChainAuthConnector::HiChainAuthConnector() HiChainAuthConnector::~HiChainAuthConnector() { + for (auto& pair : dmDeviceAuthCallbackMap_) { + pair.second = nullptr; + } + dmDeviceAuthCallbackMap_.clear(); + dmDeviceAuthCallback_ = nullptr; LOGI("HiChainAuthConnector::destructor."); } @@ -57,6 +65,28 @@ int32_t HiChainAuthConnector::RegisterHiChainAuthCallback(std::shared_ptr callback) +{ + std::lock_guard lock(dmDeviceAuthCallbackMutex_); + dmDeviceAuthCallbackMap_[id] = callback; + return DM_OK; +} + +std::shared_ptr HiChainAuthConnector::GetDeviceAuthCallback(int64_t id) +{ + if (dmDeviceAuthCallbackMap_.find(id) != dmDeviceAuthCallbackMap_.end()) { + LOGD("HiChainAuthConnector::GetDeviceAuthCallback dmDeviceAuthCallbackMap_ id: %{public}" PRId64 ".", id); + return dmDeviceAuthCallbackMap_[id]; + } + LOGD("HiChainAuthConnector::GetDeviceAuthCallback dmDeviceAuthCallbackMap_ not found, id: %{public}" + PRId64 ".", id); + // If the callback registered by the new protocol ID cannot be found, the callback registered + // by the old protocol is used. However, the old protocol callback may be empty. + return dmDeviceAuthCallback_; +} + int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId) { LOGI("HiChainAuthConnector::AuthDevice start."); @@ -89,39 +119,172 @@ int32_t HiChainAuthConnector::ProcessAuthData(int64_t requestId, std::string aut return DM_OK; } +int32_t HiChainAuthConnector::ProcessCredData(int64_t authReqId, const std::string &data) +{ + LOGI("HiChainAuthConnector::ProcessCredData start."); + const CredAuthManager *credAuthManager = GetCredAuthInstance(); + int32_t ret = credAuthManager->processCredData(authReqId, reinterpret_cast(data.c_str()), + data.length(), &deviceAuthCallback_); + if (ret != HC_SUCCESS) { + LOGE("Hichain processData failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + LOGI("HiChainAuthConnector::ProcessCredData leave."); + return DM_OK; +} + +int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::string &authParams, std::string &credId) +{ + LOGI("HiChainAuthConnector::AddCredential start."); + LOGI("HiChainAuthConnector::AddCredential osAccount=%{public}d, authParams=%{public}s\n", + osAccountId, authParams.c_str()); + char *returnData = NULL; + const CredManager *credManager = GetCredMgrInstance(); + int32_t ret = credManager->addCredential(osAccountId, authParams.c_str(), &returnData); + if (ret != HC_SUCCESS || returnData == NULL) { + LOGE("Hichain addCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + LOGI("HiChainAuthConnector::AddCredential addCredential success ret=%{public}d, returnData=%{public}s.", + ret, returnData); + credId = std::string(returnData); + LOGI("HiChainAuthConnector::AddCredential addCredId=%{public}s.", credId.c_str()); + credManager->destroyInfo(&returnData); + LOGI("HiChainAuthConnector::AddCredential leave."); + return DM_OK; +} + +int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::string &credId, std::string &publicKey) +{ + LOGI("HiChainAuthConnector::ExportCredential start. osAccountId=%{public}d, credId=%{public}s", + osAccountId, credId.c_str()); + char *returnData = NULL; + const CredManager *credManager = GetCredMgrInstance(); + int32_t ret = credManager->exportCredential(osAccountId, credId.c_str(), &returnData); + if (ret != HC_SUCCESS || returnData == NULL) { + LOGE("Hichain exportCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + + JsonObject jsonAuthParam(returnData); + credManager->destroyInfo(&returnData); + if (jsonAuthParam.IsDiscarded() || !jsonAuthParam["keyValue"].IsString()) { + LOGE("Hichain exportCredential failed, returnData is invalid."); + return ERR_DM_FAILED; + } + + publicKey = jsonAuthParam["keyValue"].Get(); + LOGI("HiChainAuthConnector::ExportCredential leave. publicKey=%{public}s", publicKey.c_str()); + return DM_OK; +} + +int32_t HiChainAuthConnector::AgreeCredential(int32_t osAccountId, const std::string selfCredId, + const std::string &authParams, std::string &credId) +{ + LOGI("HiChainAuthConnector::AgreeCredential start."); + LOGI("HiChainAuthConnector::AgreeCredential osAccountId=%{public}d, selfCredId=%{public}s, authParams=%{public}s\n", + osAccountId, selfCredId.c_str(), authParams.c_str()); + char *returnData = NULL; + const CredManager *credManager = GetCredMgrInstance(); + int32_t ret = credManager->agreeCredential(osAccountId, selfCredId.c_str(), authParams.c_str(), &returnData); + if (ret != HC_SUCCESS || returnData == NULL) { + LOGE("Hichain agreeCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + credId = returnData; + credManager->destroyInfo(&returnData); + LOGI("HiChainAuthConnector::AgreeCredential leave agreeCredId=%{public}s.", credId.c_str()); + return DM_OK; +} + +int32_t HiChainAuthConnector::DeleteCredential(int32_t osAccountId, const std::string &credId) +{ + LOGI("HiChainAuthConnector::DeleteCredential start. osAccountId=%{public}d, credId=%{public}s", osAccountId, + credId.c_str()); + const CredManager *credManager = GetCredMgrInstance(); + int32_t ret = credManager->deleteCredential(osAccountId, credId.c_str()); + if (ret != HC_SUCCESS) { + LOGE("Hichain deleteCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + LOGI("HiChainAuthConnector::DeleteCredential leave."); + return DM_OK; +} + +int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, + const std::string &pinCode) +{ + LOGI("HiChainAuthConnector::AuthCredential start. osAccountId=%{public}d, credId=%{public}s", osAccountId, + credId.c_str()); + if (credId.empty() && pinCode.empty()) { + LOGE("HiChainAuthConnector::AuthCredential failed, credId and pinCode is empty."); + return ERR_DM_FAILED; + } + + JsonObject jsonAuthParam; + if (!credId.empty()) { + jsonAuthParam["credId"] = credId; + } + if (!pinCode.empty()) { + jsonAuthParam["pinCode"] = pinCode; + } + std::string authParams = jsonAuthParam.Dump(); + + const CredAuthManager *credAuthManager = GetCredAuthInstance(); + int32_t ret = credAuthManager->authCredential(osAccountId, authReqId, authParams.c_str(), &deviceAuthCallback_); + if (ret != HC_SUCCESS) { + LOGE("HiChainAuthConnector::AuthCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + LOGI("HiChainAuthConnector::AuthCredential leave."); + return DM_OK; +} + +int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode) +{ + LOGI("HiChainAuthConnector::AuthCredential start."); + if (pinCode == INVALID_PINCODE) { + LOGE("HiChainAuthConnector::AuthCredentialPinCode failed, pinCode is empty."); + return ERR_DM_FAILED; + } + + JsonObject jsonAuthParam; + + jsonAuthParam[FIELD_PIN_CODE] = std::to_string(pinCode); + jsonAuthParam[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); + + std::string authParams = jsonAuthParam.Dump(); + + const CredAuthManager *credAuthManager = GetCredAuthInstance(); + int32_t ret = credAuthManager->authCredential(osAccountId, authReqId, authParams.c_str(), &deviceAuthCallback_); + if (ret != HC_SUCCESS) { + LOGE("HiChainAuthConnector::AuthCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + + return DM_OK; +} + bool HiChainAuthConnector::onTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) { LOGI("AuthDevice onTransmit, requestId %{public}" PRId64, requestId); - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onTransmit dmDeviceAuthCallback_ is nullptr."); return false; } - return dmDeviceAuthCallback_->AuthDeviceTransmit(requestId, data, dataLen); + return dmDeviceAuthCallback->AuthDeviceTransmit(requestId, data, dataLen); } char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, const char *reqParams) { LOGI("HiChainAuthConnector::onRequest start."); - (void)requestId; - (void)reqParams; - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onRequest dmDeviceAuthCallback_ is nullptr."); return nullptr; } - JsonObject jsonObj; - int32_t pinCode = INVALID_PINCODE; - if (dmDeviceAuthCallback_->GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { - jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; - } else { - jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; - jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); - } - std::string deviceId = ""; - dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); - jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; - std::string jsonStr = SafetyDump(jsonObj); - char *buffer = strdup(jsonStr.c_str()); - return buffer; + return dmDeviceAuthCallback->AuthDeviceRequest(requestId, operationCode, reqParams); } void HiChainAuthConnector::onFinish(int64_t requestId, int operationCode, const char *returnData) @@ -129,11 +292,12 @@ void HiChainAuthConnector::onFinish(int64_t requestId, int operationCode, const LOGI("HiChainAuthConnector::onFinish reqId:%{public}" PRId64 ", operation:%{public}d.", requestId, operationCode); (void)returnData; - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onFinish dmDeviceAuthCallback_ is nullptr."); return; } - dmDeviceAuthCallback_->AuthDeviceFinish(requestId); + dmDeviceAuthCallback->AuthDeviceFinish(requestId); } void HiChainAuthConnector::onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn) @@ -142,7 +306,8 @@ void HiChainAuthConnector::onError(int64_t requestId, int operationCode, int err requestId, operationCode, errorCode); (void)operationCode; (void)errorReturn; - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onError dmDeviceAuthCallback_ is nullptr."); return; } @@ -150,17 +315,18 @@ void HiChainAuthConnector::onError(int64_t requestId, int operationCode, int err if (errorCode == PROOF_MISMATCH) { dmErrorCode = ERR_DM_HICHAIN_PROOFMISMATCH; } - dmDeviceAuthCallback_->AuthDeviceError(requestId, dmErrorCode); + dmDeviceAuthCallback->AuthDeviceError(requestId, dmErrorCode); } void HiChainAuthConnector::onSessionKeyReturned(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) { LOGI("HiChainAuthConnector::onSessionKeyReturned start."); - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onSessionKeyReturned dmDeviceAuthCallback_ is nullptr."); return; } - dmDeviceAuthCallback_->AuthDeviceSessionKey(requestId, sessionKey, sessionKeyLen); + dmDeviceAuthCallback->AuthDeviceSessionKey(requestId, sessionKey, sessionKeyLen); } int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey) @@ -198,6 +364,70 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t return DM_OK; } +int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, const JsonObject &queryParams, + JsonObject &resultJson) +{ + int32_t ret; + + const CredManager *cm = GetCredMgrInstance(); + char *credIdList = nullptr; + ret = cm->queryCredentialByParams(userId, queryParams.Dump().c_str(), + &credIdList); + if (ret != DM_OK) { + LOGE("HiChainAuthConnector::QueryCredentialInfo fail to query credential id list with ret %{public}d.", ret); + return ERR_DM_FAILED; + } + JsonObject credIdListJson(credIdList); + FreeJsonString(credIdList); + if (credIdListJson.IsDiscarded()) { + LOGE("HiChainAuthConnector::QueryCredentialInfo credential id list to jsonStr error"); + return ERR_DM_FAILED; + } + + for (const auto& element : credIdListJson.Items()) { + if (!element.IsString()) { + continue; + } + std::string credId = element.Get(); + + char *returnCredInfo = nullptr; + ret = cm->queryCredInfoByCredId(userId, credId.c_str(), &returnCredInfo); + if (ret != DM_OK) { + LOGE("HiChainAuthConnector::QueryCredentialInfo fail to query credential info."); + return ERR_DM_FAILED; + } + JsonObject credInfoJson(returnCredInfo); + FreeJsonString(returnCredInfo); + if (credInfoJson.IsDiscarded()) { + LOGE("HiChainAuthConnector::QueryCredentialInfo credential info jsonStr error"); + return ERR_DM_FAILED; + } + + resultJson.Insert(credId, credInfoJson); + } + + return DM_OK; +} + +int32_t HiChainAuthConnector::QueryCredInfoByCredId(int32_t userId, std::string credId, JsonObject &resultJson) +{ + const CredManager *cm = GetCredMgrInstance(); + char *returnCredInfo = nullptr; + int32_t ret = cm->queryCredInfoByCredId(userId, credId.c_str(), &returnCredInfo); + if (ret != DM_OK) { + LOGE("[HICHAIN]::QueryCredInfoByCredId failed, ret: %{public}d.", ret); + return ret; + } + JsonObject credInfoJson(returnCredInfo); + FreeJsonString(returnCredInfo); + if (credInfoJson.IsDiscarded()) { + LOGE("QueryCredInfoByCredId credential info jsonStr error"); + return ERR_DM_FAILED; + } + resultJson.Insert(credId, credInfoJson); + return DM_OK; +} + bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAccountId) { LOGI("HiChainAuthConnector::QueryCredential start."); diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 0af963094..c1e3efc42 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -92,7 +92,7 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId, bool isForceJoin) { std::string connectAddr; LOGI("start, deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - ConnectionAddr *addrInfo = GetConnectAddr(deviceId, connectAddr); + auto addrInfo = GetConnectAddr(deviceId, connectAddr); if (addrInfo == nullptr) { LOGE("addrInfo is nullptr."); return; @@ -102,13 +102,68 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId, bool isForceJoin) LOGE("convert remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash_).c_str()); return; } - int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult, isForceJoin); + int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo.get(), OnSoftbusJoinLNNResult, isForceJoin); if (ret != DM_OK) { LOGE("[SOFTBUS]JoinLNN failed, ret: %{public}d.", ret); } return; } +void SoftbusConnector::JoinLnn(const std::string &deviceId, const std::string &remoteUdidHash) +{ + std::string connectAddr; + LOGI("start, deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); + auto addrInfo = GetConnectAddr(deviceId, connectAddr); + if (addrInfo == nullptr) { + LOGE("addrInfo is nullptr."); + return; + } + if (Crypto::ConvertHexStringToBytes(addrInfo->info.ble.udidHash, UDID_HASH_LEN, + remoteUdidHash.c_str(), remoteUdidHash.length()) != DM_OK) { + LOGE("convert remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash).c_str()); + return; + } + int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo.get(), OnSoftbusJoinLNNResult, false); + if (ret != DM_OK) { + LOGE("[SOFTBUS]JoinLNN failed, ret: %{public}d.", ret); + } + return; +} + +void SoftbusConnector::JoinLNNBySkId(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId, + std::string udid, std::string udidHash) +{ + LOGI("start, JoinLNNBySkId sessionId: %{public}d, udid: %{public}s.", sessionId, GetAnonyString(udid).c_str()); + std::string connectAddr; + auto addrInfo = GetConnectAddr(udid, connectAddr); + if (addrInfo == nullptr) { + LOGE("addrInfo is nullptr."); + return; + } + LOGI("addrInfo->type: %{public}d", addrInfo->type); + if (addrInfo->type == CONNECTION_ADDR_BLE) { + if (Crypto::ConvertHexStringToBytes(addrInfo->info.ble.udidHash, UDID_HASH_LEN, udidHash.c_str(), + udidHash.length()) != DM_OK) { + LOGE("convert remoteUdid hash failed, udidHash: %{public}s.", GetAnonyString(udidHash).c_str()); + return; + } + } + + addrInfo->deviceKeyId.hasDeviceKeyId = true; // 总线修改后适配 + if (sessionKeyId > 0 && remoteSessionKeyId > 0) { + addrInfo->deviceKeyId.localDeviceKeyId = sessionKeyId; // 总线修改后适配 + addrInfo->deviceKeyId.remoteDeviceKeyId = remoteSessionKeyId; // 总线修改后适配 + LOGI("sessionKeyId valid"); + } else { + addrInfo->deviceKeyId.localDeviceKeyId = 0; // 总线修改后适配 + addrInfo->deviceKeyId.remoteDeviceKeyId = 0; // 总线修改后适配 + } + int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo.get(), OnSoftbusJoinLNNResult, false); + if (ret != DM_OK) { + LOGE("[SOFTBUS]JoinLNNBySkId failed, ret: %{public}d.", ret); + } +} + void SoftbusConnector::JoinLnnByHml(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId) { LOGI("start, JoinLnnByHml sessionId: %{public}d.", sessionId); @@ -116,12 +171,12 @@ void SoftbusConnector::JoinLnnByHml(int32_t sessionId, int32_t sessionKeyId, int addrInfo.type = CONNECTION_ADDR_SESSION_WITH_KEY; addrInfo.info.session.sessionId = sessionId; if (sessionKeyId > 0 && remoteSessionKeyId > 0) { - addrInfo.info.session.localDeviceKeyId = sessionKeyId; - addrInfo.info.session.remoteDeviceKeyId = remoteSessionKeyId; + addrInfo.deviceKeyId.localDeviceKeyId = sessionKeyId; + addrInfo.deviceKeyId.remoteDeviceKeyId = remoteSessionKeyId; LOGI("sessionKeyId valid"); } else { - addrInfo.info.session.localDeviceKeyId = 0; - addrInfo.info.session.remoteDeviceKeyId = 0; + addrInfo.deviceKeyId.localDeviceKeyId = 0; + addrInfo.deviceKeyId.remoteDeviceKeyId = 0; } int32_t ret = ::JoinLNN(DM_PKG_NAME, &addrInfo, OnSoftbusJoinLNNResult, false); if (ret != DM_OK) { @@ -172,52 +227,59 @@ ConnectionAddr *SoftbusConnector::GetConnectAddrByType(DeviceInfo *deviceInfo, C return nullptr; } -ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, std::string &connectAddr) +std::shared_ptr SoftbusConnector::GetDeviceInfoFromMap(const std::string &deviceId) { - DeviceInfo *deviceInfo = nullptr; - { - std::lock_guard lock(discoveryDeviceInfoMutex_); - auto iter = discoveryDeviceInfoMap_.find(deviceId); - if (iter == discoveryDeviceInfoMap_.end()) { - LOGE("deviceInfo not found by deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - return nullptr; - } - deviceInfo = iter->second.get(); + std::lock_guard lock(discoveryDeviceInfoMutex_); + auto iter = discoveryDeviceInfoMap_.find(deviceId); + if (iter == discoveryDeviceInfoMap_.end()) { + LOGE("deviceInfo not found by deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); + return nullptr; } + return iter->second; +} + +std::shared_ptr SoftbusConnector::GetConnectAddr(const std::string &deviceId, std::string &connectAddr) +{ + std::shared_ptr deviceInfo = GetDeviceInfoFromMap(deviceId); if (deviceInfo->addrNum <= 0 || deviceInfo->addrNum >= CONNECTION_ADDR_MAX) { LOGE("deviceInfo addrNum not valid, addrNum: %{public}d.", deviceInfo->addrNum); return nullptr; } JsonObject jsonPara; - ConnectionAddr *addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_ETH); + std::shared_ptr connectAddrPtr = std::make_shared(); + ConnectionAddr *addr = GetConnectAddrByType(deviceInfo.get(), ConnectionAddrType::CONNECTION_ADDR_ETH); if (addr != nullptr) { + *connectAddrPtr = *addr; LOGI("[SOFTBUS]get ETH ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); jsonPara[ETH_IP] = addr->info.ip.ip; jsonPara[ETH_PORT] = addr->info.ip.port; - connectAddr = SafetyDump(jsonPara); - return addr; + connectAddr = jsonPara.Dump(); + return connectAddrPtr; } - addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN); + addr = GetConnectAddrByType(deviceInfo.get(), ConnectionAddrType::CONNECTION_ADDR_WLAN); if (addr != nullptr) { + *connectAddrPtr = *addr; jsonPara[WIFI_IP] = addr->info.ip.ip; jsonPara[WIFI_PORT] = addr->info.ip.port; LOGI("[SOFTBUS]get WLAN ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = SafetyDump(jsonPara); - return addr; + connectAddr = jsonPara.Dump(); + return connectAddrPtr; } - addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR); + addr = GetConnectAddrByType(deviceInfo.get(), ConnectionAddrType::CONNECTION_ADDR_BR); if (addr != nullptr) { + *connectAddrPtr = *addr; jsonPara[BR_MAC] = addr->info.br.brMac; LOGI("[SOFTBUS]get BR ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = SafetyDump(jsonPara); - return addr; + connectAddr = jsonPara.Dump(); + return connectAddrPtr; } - addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE); + addr = GetConnectAddrByType(deviceInfo.get(), ConnectionAddrType::CONNECTION_ADDR_BLE); if (addr != nullptr) { + *connectAddrPtr = *addr; jsonPara[BLE_MAC] = addr->info.ble.bleMac; - connectAddr = SafetyDump(jsonPara); + connectAddr = jsonPara.Dump(); addr->info.ble.priority = BLE_PRIORITY_HIGH; - return addr; + return connectAddrPtr; } LOGE("[SOFTBUS]failed to get ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); return nullptr; @@ -455,7 +517,8 @@ void SoftbusConnector::DeleteOffLineTimer(std::string &udidHash) } } -bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) +// isHash:传入的deviceId是否为哈希值 +bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceIdHash, bool isHash) { LOGI("Check the device is online."); int32_t deviceCount = 0; @@ -472,7 +535,8 @@ bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) LOGE("[SOFTBUS]GetNodeKeyInfo failed."); } std::string udid = reinterpret_cast(mUdid); - if (udid == targetDeviceId) { + if ((isHash == false && udid == targetDeviceIdHash) || + (isHash == true && Crypto::Sha256(udid).find(targetDeviceIdHash) == 0)) { LOGI("The device is online."); FreeNodeInfo(nodeInfo); return true; @@ -483,6 +547,11 @@ bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) return false; } +bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) +{ + return CheckIsOnline(targetDeviceId, false); +} + DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &deviceId) { LOGI("SoftbusConnector::GetDeviceInfoBydeviceId"); diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index 125ffce5a..393105765 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -33,48 +33,9 @@ std::shared_ptr SoftbusSession::sessionCallback_ = null constexpr const char* DM_HITRACE_AUTH_TO_OPPEN_SESSION = "DM_HITRACE_AUTH_TO_OPPEN_SESSION"; constexpr int32_t MAX_DATA_LEN = 65535; -static void OnShutdown(int32_t socket, ShutdownReason reason) -{ - LOGI("[SOFTBUS]OnShutdown socket : %{public}d, reason: %{public}d", socket, (int32_t)reason); - SoftbusSession::OnSessionClosed(socket); -} - -static void OnBytes(int32_t socket, const void *data, uint32_t dataLen) -{ - LOGI("[SOFTBUS]OnBytes socket : %{public}d", socket); - SoftbusSession::OnBytesReceived(socket, data, dataLen); -} - -static void OnQos(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount) -{ - LOGI("[SOFTBUS]OnQos, socket: %{public}d, QoSEvent: %{public}d, qosCount: %{public}u", socket, (int32_t)eventId, - qosCount); - if (qosCount > QOS_TYPE_BUTT) { - LOGE("OnQos invalid qosCount"); - return; - } - for (uint32_t idx = 0; idx < qosCount; idx++) { - LOGI("QosTV: type: %{public}d, value: %{public}d", (int32_t)qos[idx].qos, qos[idx].value); - } -} - SoftbusSession::SoftbusSession() { LOGD("SoftbusSession constructor."); - if (memset_s(&iSocketListener_, sizeof(ISocketListener), 0, sizeof(ISocketListener)) != DM_OK) { - LOGE("SoftbusSession::SoftbusSession memset_s failed."); - return; - } - - iSocketListener_.OnShutdown = OnShutdown; - iSocketListener_.OnBytes = OnBytes; - iSocketListener_.OnQos = OnQos; - iSocketListener_.OnFile = nullptr; - iSocketListener_.OnMessage = nullptr; - iSocketListener_.OnBind = nullptr; - iSocketListener_.OnStream = nullptr; - iSocketListener_.OnError = nullptr; - iSocketListener_.OnNegotiate = nullptr; } SoftbusSession::~SoftbusSession() @@ -99,12 +60,12 @@ int32_t SoftbusSession::OpenAuthSession(const std::string &deviceId) DmTraceStart(std::string(DM_HITRACE_AUTH_TO_OPPEN_SESSION)); int32_t sessionId = -1; std::string connectAddr; - ConnectionAddr *addrInfo = SoftbusConnector::GetConnectAddr(deviceId, connectAddr); + auto addrInfo = SoftbusConnector::GetConnectAddr(deviceId, connectAddr); if (addrInfo == nullptr) { LOGE("[SOFTBUS]addrInfo is nullptr. sessionId: %{public}d.", sessionId); return sessionId; } - sessionId = ::OpenAuthSession(DM_SESSION_NAME, addrInfo, 1, nullptr); + sessionId = ::OpenAuthSession(DM_SESSION_NAME, addrInfo.get(), 1, nullptr); if (sessionId < 0) { LOGE("[SOFTBUS]open session error, sessionId: %{public}d.", sessionId); return sessionId; @@ -161,20 +122,6 @@ int32_t SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevI int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) { - JsonObject jsonObject(message); - if (jsonObject.IsDiscarded()) { - LOGE("extrasJson error, message: %{public}s.", GetAnonyString(message).c_str()); - return ERR_DM_FAILED; - } - if (!IsInt32(jsonObject, TAG_MSG_TYPE)) { - LOGE("SoftbusSession::SendData err json string."); - return ERR_DM_FAILED; - } - int32_t msgType = jsonObject[TAG_MSG_TYPE].Get(); - LOGI("start, msgType: %{public}d.", msgType); - if (sessionCallback_->GetIsCryptoSupport()) { - LOGI("SendData Start encryption."); - } int32_t ret = SendBytes(sessionId, message.c_str(), strlen(message.c_str())); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed."); @@ -195,9 +142,13 @@ int32_t SoftbusSession::SendHeartbeatData(int32_t sessionId, std::string &messag int SoftbusSession::OnSessionOpened(int sessionId, int result) { + LOGD("OnSessionOpened, success, sessionId: %{public}d.", sessionId); + if (sessionCallback_ == nullptr) { + LOGD("Session callback is not registered."); + return DM_OK; + } int32_t sessionSide = GetSessionSide(sessionId); sessionCallback_->OnSessionOpened(sessionId, sessionSide, result); - LOGD("OnSessionOpened, success, sessionId: %{public}d.", sessionId); return DM_OK; } @@ -206,36 +157,7 @@ void SoftbusSession::OnSessionClosed(int sessionId) LOGI("OnSessionClosed, sessionId: %{public}d.", sessionId); CHECK_NULL_VOID(sessionCallback_); sessionCallback_->OnSessionClosed(sessionId); -} - -void SoftbusSession::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) -{ - if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > MAX_DATA_LEN) { - LOGI("[SOFTBUS]fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.", sessionId, - dataLen); - return; - } - LOGI("start, sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); - if (sessionCallback_->GetIsCryptoSupport()) { - LOGI("Start decryption."); - } - std::string message = std::string(reinterpret_cast(data), dataLen); - JsonObject jsonObject(message); - if (jsonObject.IsDiscarded()) { - LOGE("DecodeRequestAuth jsonStr error"); - return; - } - if (!IsInt32(jsonObject, TAG_MSG_TYPE)) { - LOGE("err json string, first time"); - return; - } - if (jsonObject[TAG_MSG_TYPE].Get() == AUTH_DEVICE_REQ_NEGOTIATE || - jsonObject[TAG_MSG_TYPE].Get() == AUTH_DEVICE_RESP_NEGOTIATE) { - sessionCallback_->OnAuthDeviceDataReceived(sessionId, message); - } else { - sessionCallback_->OnDataReceived(sessionId, message); - } - LOGI("completed."); + return; } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 8490589fc..b0ce662dc 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -15,9 +15,13 @@ #include "device_manager_service_impl.h" +#include +#include +#include #include #include "app_manager.h" +#include "dm_error_type.h" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" @@ -26,28 +30,357 @@ #include "dm_radar_helper.h" #include "dm_softbus_cache.h" #include "multiple_user_connector.h" +#include "ipc_skeleton.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "dm_common_event_manager.h" #include "parameter.h" +#include "dm_random.h" #include "common_event_support.h" using namespace OHOS::EventFwk; #endif namespace OHOS { namespace DistributedHardware { + +namespace { + // One year 365 * 24 * 60 * 60 constexpr int32_t MAX_ALWAYS_ALLOW_SECONDS = 31536000; +constexpr int32_t MIN_PIN_CODE = 100000; +constexpr int32_t MAX_PIN_CODE = 999999; +// New protocol field definition. To avoid dependency on the new protocol header file, +// do not directly depend on the new protocol header file. +constexpr int32_t MSG_TYPE_REQ_ACL_NEGOTIATE = 80; +constexpr int32_t MSG_TYPE_RESP_ACL_NEGOTIATE = 90; +constexpr int32_t MSG_TYPE_REQ_AUTH_TERMINATE = 104; +constexpr int32_t AUTH_SRC_FINISH_STATE = 12; +constexpr int32_t MAX_DATA_LEN = 65535; +constexpr const char* DM_TAG_LOGICAL_SESSION_ID = "logicalSessionId"; +constexpr const char* DM_TAG_PEER_DISPLAY_ID = "peerDisplayId"; +constexpr const char* DM_TAG_ACCESSEE_USER_ID = "accesseeUserId"; +constexpr const char* DM_TAG_EXTRA_INFO = "extraInfo"; + +static bool IsMessageOldVersion(const JsonObject &jsonObject, std::shared_ptr session) +{ + std::string dmVersion = ""; + std::string edition = ""; + if (jsonObject[TAG_DMVERSION].IsString()) { + dmVersion = jsonObject[TAG_DMVERSION].Get(); + } + if (jsonObject[TAG_EDITION].IsString()) { + edition = jsonObject[TAG_EDITION].Get(); + } + dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); + + // Assign the physical session version and release the semaphore. + session->version_ = dmVersion; + + // If the version number is higher than 5.0.4 (the highest version of the old protocol), + // there is no need to switch to the old protocol. + if (CompareVersion(dmVersion, DM_VERSION_5_0_OLD_MAX) == true) { + return false; + } + + return true; +} + +std::string CreateTerminateMessage(void) +{ + JsonObject jsonObject; + jsonObject[TAG_MSG_TYPE] = MSG_TYPE_REQ_AUTH_TERMINATE; + jsonObject[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; + jsonObject[TAG_AUTH_FINISH] = false; + + return jsonObject.Dump(); +} + +} + +std::condition_variable DeviceManagerServiceImpl::cleanEventCv_; +std::mutex DeviceManagerServiceImpl::cleanEventMutex_; +std::queue DeviceManagerServiceImpl::cleanEventQueue_; + +Session::Session(int sessionId, std::string deviceId) +{ + sessionId_ = sessionId; + deviceId_ = deviceId; +} DeviceManagerServiceImpl::DeviceManagerServiceImpl() { + running_ = true; + thread_ = std::thread(&DeviceManagerServiceImpl::CleanWorker, this); LOGI("DeviceManagerServiceImpl constructor"); } DeviceManagerServiceImpl::~DeviceManagerServiceImpl() { + Stop(); + thread_.join(); LOGI("DeviceManagerServiceImpl destructor"); } +static uint64_t StringToUint64(const std::string& str) +{ + // Calculate the length of the substring, taking the minimum of the string length and 8 + size_t subStrLength = std::min(str.length(), static_cast(8U)); + + // Extract substring + std::string substr = str.substr(str.length() - subStrLength); + + // Convert substring to uint64_t + uint64_t result = 0; + for (size_t i = 0; i < subStrLength; ++i) { + result <<= 8; // Shift left 8 bits + result |= static_cast(substr[i]); + } + + return result; +} + + +static uint64_t GetTokenId(bool isSrcSide, int32_t displayId, std::string &bundleName) +{ + uint64_t tokenId = 0; + if (isSrcSide) { + // src end + tokenId = IPCSkeleton::GetCallingTokenID(); + } else { + // sink end + int64_t tmpTokenId; + // get userId + int32_t targetUserId = AuthManagerBase::DmGetUserId(displayId); + if (targetUserId == -1) { + return tokenId; + } + if (AppManager::GetInstance().GetHapTokenIdByName(targetUserId, bundleName, 0, tmpTokenId) == DM_OK) { + tokenId = static_cast(tmpTokenId); + } else if (AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tmpTokenId) == DM_OK) { + tokenId = static_cast(tmpTokenId); + } else { + // get deviceId, take the 8 character value as tokenId + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string deviceId = std::string(localDeviceId); + if (deviceId.length() != 0) { + tokenId = StringToUint64(deviceId); + } + } + } + return tokenId; +} + +int64_t DeviceManagerServiceImpl::FetchCleanEvent() +{ + std::unique_lock lock(cleanEventMutex_); + cleanEventCv_.wait(lock, [&] { + return !running_.load() || !cleanEventQueue_.empty(); + }); + + if (!running_.load()) return 0; + + int64_t logicalSessionId = cleanEventQueue_.front(); + cleanEventQueue_.pop(); + return logicalSessionId; +} + +void DeviceManagerServiceImpl::CleanWorker() +{ + while (running_.load()) { + auto logicalSessionId = FetchCleanEvent(); + LOGI("DeviceManagerServiceImpl::CleanWorker clean auth_mgr, its logicalSessionId: %{public}" PRId64 "", + logicalSessionId); + CleanAuthMgrByLogicalSessionId(logicalSessionId); + } + LOGI("DeviceManagerServiceImpl::CleanWorker end"); +} + +void DeviceManagerServiceImpl::Stop() +{ + running_.store(false); + cleanEventCv_.notify_all(); + std::lock_guard lock(cleanEventMutex_); + while (!cleanEventQueue_.empty()) { + int64_t logicalSessionId = cleanEventQueue_.front(); + cleanEventQueue_.pop(); + CleanAuthMgrByLogicalSessionId(logicalSessionId); + } +} + +void DeviceManagerServiceImpl::NotifyCleanEvent(int64_t logicalSessionId) +{ + LOGI("DeviceManagerServiceImpl::NotifyCleanEvent logicalSessionId: %{public}" PRId64 ".", logicalSessionId); + std::lock_guard lock(cleanEventMutex_); + // Store into the queue + cleanEventQueue_.push(logicalSessionId); + cleanEventCv_.notify_one(); +} + +void DeviceManagerServiceImpl::ImportConfig(std::shared_ptr authMgr, uint64_t tokenId) +{ + // Import configuration + if (configsMap_.find(tokenId) != configsMap_.end()) { + authMgr->ImportAuthCode(configsMap_[tokenId]->pkgName, configsMap_[tokenId]->authCode); + authMgr->RegisterAuthenticationType(configsMap_[tokenId]->authenticationType); + LOGI("DeviceManagerServiceImpl::ImportConfig import authCode Successful."); + } + return; +} + +int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_t tokenId, + std::shared_ptr session, int64_t logicalSessionId) +{ + if (session == nullptr) { + LOGE("InitAndRegisterAuthMgr, The physical link is not created."); + return ERR_DM_AUTH_OPEN_SESSION_FAILED; + } + // If version is empty, allow creation for the first time, create a new protocol auth_mgr to negotiate version; + // subsequent creations wait, and directly use version to create the corresponding auth_mgr after release. + if (session->version_ == "") { + bool expected = false; + if (session->flag_.compare_exchange_strong(expected, true)) { + LOGI("The physical link is being created and the dual-end device version is aligned."); + } else { + // Do not allow simultaneous version negotiation, return error directly + LOGE("Version negotiation is not allowed at the same time."); + return ERR_DM_AUTH_BUSINESS_BUSY; + } + } + if (session->version_ == "" || CompareVersion(session->version_, DM_VERSION_5_0_OLD_MAX)) { + // First time creation or new protocol + if (authMgrMap_.find(tokenId) == authMgrMap_.end()) { + // Create a new auth_mgr, create authMgrMap_[tokenId] + if (isSrcSide) { + // src end + authMgrMap_[tokenId] = std::make_shared(softbusConnector_, + listener_, hiChainAuthConnector_); + } else { + // sink end + authMgrMap_[tokenId] = std::make_shared(softbusConnector_, + listener_, hiChainAuthConnector_); + } + // Register resource destruction notification function + authMgrMap_[tokenId]->RegisterCleanNotifyCallback(&DeviceManagerServiceImpl::NotifyCleanEvent); + hiChainAuthConnector_->RegisterHiChainAuthCallbackById(logicalSessionId, authMgrMap_[tokenId]); + LOGI("DeviceManagerServiceImpl::Initialize authMgrMap_ token: %{public}" PRId64 ".", tokenId); + ImportConfig(authMgrMap_[tokenId], tokenId); + return DM_OK; + } + } else { + LOGI("DeviceManagerServiceImpl::InitAndRegisterAuthMgr old authMgr."); + if (authMgr_ == nullptr) { + // Create old auth_mar, only create an independent one + authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener_, + hiChainAuthConnector_); + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); + hiChainConnector_->RegisterHiChainCallback(authMgr_); + hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); + ImportConfig(authMgr_, tokenId); + } + return DM_OK; + } + // authMgr_ has been created, indicating that a binding event already exists. + // Other requests are rejected, and an error code is returned. + LOGE("BindTarget failed, this device is being bound. Please try again later."); + return ERR_DM_AUTH_BUSINESS_BUSY; +} + +void DeviceManagerServiceImpl::CleanSessionMap(int sessionId, std::shared_ptr session) +{ + session->logicalSessionCnt_.fetch_sub(1); + if (session->logicalSessionCnt_.load(std::memory_order_relaxed) == 0) { + softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); + std::lock_guard lock(mapMutex_); + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + sessionsMap_[sessionId] = nullptr; + sessionsMap_.erase(sessionId); + } + if (deviceId2SessionIdMap_.find(session->deviceId_) != deviceId2SessionIdMap_.end()) { + deviceId2SessionIdMap_.erase(session->deviceId_); + } + } + return; +} + +void DeviceManagerServiceImpl::CleanSessionMapByLogicalSessionId(int64_t logicalSessionId) +{ + if (logicalSessionId2SessionIdMap_.find(logicalSessionId) != logicalSessionId2SessionIdMap_.end()) { + auto sessionId = logicalSessionId2SessionIdMap_[logicalSessionId]; + auto session = GetCurSession(sessionId); + if (session != nullptr) { + CleanSessionMap(sessionId, session); + } + logicalSessionId2SessionIdMap_.erase(logicalSessionId); + } + logicalSessionId2TokenIdMap_.erase(logicalSessionId); + return; +} + +void DeviceManagerServiceImpl::CleanAuthMgrByLogicalSessionId(int64_t logicalSessionId) +{ + uint64_t tokenId = 0; + if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) { + tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; + } + + if (configsMap_.find(tokenId) != configsMap_.end()) { + configsMap_[tokenId] = nullptr; + configsMap_.erase(tokenId); + } + + CleanSessionMapByLogicalSessionId(logicalSessionId); + + if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { + authMgrMap_[tokenId] = nullptr; + authMgrMap_.erase(tokenId); + } + return; +} + +std::shared_ptr DeviceManagerServiceImpl::GetAuthMgr() +{ + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { + LOGI("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ token: %{public}" PRId64 ".", tokenId); + return authMgrMap_[tokenId]; + } + LOGE("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ not found, token: %{public}" PRId64 ".", tokenId); + // If the new protocol's authMgr cannot be found, return the old protocol's authMgr, which may be null + return authMgr_; +} + +// Needed in the callback function +std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByTokenId(uint64_t tokenId) +{ + if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { + LOGI("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ token: %{public}" PRId64 ".", tokenId); + return authMgrMap_[tokenId]; + } + LOGE("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ not found, token: %{public}" PRId64 ".", tokenId); + // If the new protocol's authMgr cannot be found, return the old protocol's authMgr, which may be null + return authMgr_; +} + +static int64_t GenerateRandNum(int sessionId) +{ + // Get the current timestamp + auto timestamp = std::chrono::duration_cast(std::chrono::high_resolution_clock::now(). + time_since_epoch()).count(); + + // Generate random numbers + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_int_distribution<> rand_dis(0, 0xFFFFFFFF); + uint32_t randomNumber = rand_dis(gen); + + // Combination of random numbers + int64_t randNum = (static_cast(timestamp) << 32) | + (static_cast(sessionId) << 16) | + static_cast(randomNumber); + + return randNum; +} + int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptr &listener) { LOGI("DeviceManagerServiceImpl Initialize"); @@ -68,14 +401,6 @@ int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptrRegisterSoftbusStateCallback(); } - if (authMgr_ == nullptr) { - authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener, - hiChainAuthConnector_); - softbusConnector_->RegisterConnectorCallback(authMgr_); - softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); - hiChainConnector_->RegisterHiChainCallback(authMgr_); - hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); - } if (credentialMgr_ == nullptr) { credentialMgr_ = std::make_shared(hiChainConnector_, listener); } @@ -98,6 +423,24 @@ void DeviceManagerServiceImpl::Release() softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); hiChainConnector_->UnRegisterHiChainCallback(); authMgr_ = nullptr; + for (auto& pair : authMgrMap_) { + pair.second = nullptr; + } + authMgrMap_.clear(); + for (auto& pair : sessionsMap_) { + pair.second = nullptr; + } + sessionsMap_.clear(); + for (auto& pair : configsMap_) { + pair.second = nullptr; + } + deviceId2SessionIdMap_.clear(); + deviceIdMutexMap_.clear(); + sessionEnableMutexMap_.clear(); + sessionEnableCvMap_.clear(); + logicalSessionId2TokenIdMap_.clear(); + logicalSessionId2SessionIdMap_.clear(); + configsMap_.clear(); deviceStateMgr_ = nullptr; softbusConnector_ = nullptr; abilityMgr_ = nullptr; @@ -114,7 +457,12 @@ int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgNam pkgName.c_str(), GetAnonyString(udid).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->UnAuthenticateDevice(pkgName, udid, bindLevel); + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + return authMgr->UnAuthenticateDevice(pkgName, udid, bindLevel); } int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName) @@ -123,7 +471,12 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN LOGE("DeviceManagerServiceImpl::StopAuthenticateDevice failed"); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->StopAuthenticateDevice(pkgName); + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + return authMgr->StopAuthenticateDevice(pkgName); } int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, @@ -135,7 +488,9 @@ int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const return ERR_DM_INPUT_PARA_INVALID; } std::string extra = ""; - return authMgr_->UnBindDevice(pkgName, udid, bindLevel, extra); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + return DeleteAclV2(pkgName, std::string(localDeviceId), udid, bindLevel, extra); } int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, @@ -146,7 +501,9 @@ int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const pkgName.c_str(), GetAnonyString(udid).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->UnBindDevice(pkgName, udid, bindLevel, extra); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + return DeleteAclV2(pkgName, std::string(localDeviceId), udid, bindLevel, extra); } int32_t DeviceManagerServiceImpl::SetUserOperation(std::string &pkgName, int32_t action, @@ -157,8 +514,18 @@ int32_t DeviceManagerServiceImpl::SetUserOperation(std::string &pkgName, int32_t "%{public}s", pkgName.c_str(), params.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - if (authMgr_ != nullptr) { - authMgr_->OnUserOperation(action, params); + uint64_t tokenId = 0; + JsonObject jsonObject(params); + if (jsonObject.IsDiscarded()) { + LOGE("OnUserOperation jsonStr error"); + return ERR_DM_INPUT_PARA_INVALID; + } + if (jsonObject[TOKENID].IsNumberInteger()) { + tokenId = jsonObject[TOKENID].Get(); + } + auto authMgr = GetAuthMgrByTokenId(tokenId); + if (authMgr != nullptr) { + authMgr->OnUserOperation(action, params); } return DM_OK; } @@ -194,7 +561,7 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; processInfo.userId = item.first; softbusConnector_->SetProcessInfo(processInfo); - } else if (static_cast(item.second) == DEVICE) { + } else if (static_cast(item.second) == USER) { LOGI("The offline device is device bind type."); devInfo.authForm = DmAuthForm::PEER_TO_PEER; processInfo.userId = item.first; @@ -301,6 +668,10 @@ std::string DeviceManagerServiceImpl::GetUdidHashByNetworkId(const std::string & int DeviceManagerServiceImpl::OnSessionOpened(int sessionId, int result) { + { + std::lock_guard lock(sessionEnableMutexMap_[sessionId]); + sessionEnableCvMap_[sessionId].notify_all(); + } std::string peerUdid = ""; softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid); struct RadarInfo info = { @@ -313,17 +684,263 @@ int DeviceManagerServiceImpl::OnSessionOpened(int sessionId, int result) if (!DmRadarHelper::GetInstance().ReportAuthSessionOpenCb(info)) { LOGE("ReportAuthSessionOpenCb failed"); } + + // Get the remote deviceId, sink end gives sessionsMap[deviceId] = session; + { + std::lock_guard lock(mapMutex_); + if (sessionsMap_.find(sessionId) == sessionsMap_.end()) { + sessionsMap_[sessionId] = std::make_shared(sessionId, peerUdid); + } + } + return SoftbusSession::OnSessionOpened(sessionId, result); } void DeviceManagerServiceImpl::OnSessionClosed(int sessionId) { + auto session = GetCurSession(sessionId); + if (session != nullptr) { + std::lock_guard lock(mapMutex_); + for (const auto& logicalSessionId : session->logicalSessionSet_) { + logicalSessionId2TokenIdMap_.erase(logicalSessionId); + logicalSessionId2SessionIdMap_.erase(logicalSessionId); + } + if (deviceId2SessionIdMap_.find(session->deviceId_) != deviceId2SessionIdMap_.end()) { + deviceId2SessionIdMap_.erase(session->deviceId_); + } + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + sessionsMap_[sessionId] = nullptr; + sessionsMap_.erase(sessionId); + } + } SoftbusSession::OnSessionClosed(sessionId); } +static JsonObject GetJsonObjectFromData(const void *data, unsigned int dataLen) +{ + std::string message = std::string(reinterpret_cast(data), dataLen); + return JsonObject(message); +} + +// When downgrading the version, determine whether it is src or sink based on the message. +// src: Received 90 message. +// sink: Received 80 message. +static bool IsAuthManagerSourceByMessage(int32_t msgType) +{ + return msgType == MSG_TYPE_RESP_ACL_NEGOTIATE; +} + + +// Get the current session object +std::shared_ptr DeviceManagerServiceImpl::GetCurSession(int sessionId) +{ + std::shared_ptr curSession = nullptr; + // Get the remote deviceId, sink end gives sessionsMap[deviceId] = session; + { + std::lock_guard lock(mapMutex_); + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + curSession = sessionsMap_[sessionId]; + } else { + LOGE("OnBytesReceived, The local session cannot be found."); + } + } + return curSession; +} + +std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByMessage(int32_t msgType, + int64_t logicalSessionId, const JsonObject &jsonObject, std::shared_ptr curSession) +{ + uint64_t tokenId = 0; + if (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE) { + if (logicalSessionId != 0) { + curSession->logicalSessionSet_.insert(logicalSessionId); + std::string bundleName; + int32_t displayId = 0; + if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { + bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); + } + if (jsonObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { + displayId = jsonObject[DM_TAG_PEER_DISPLAY_ID].Get(); + } + tokenId = GetTokenId(false, displayId, bundleName); + if (tokenId == 0) { + LOGE("GetAuthMgrByMessage, Get tokenId failed."); + return nullptr; + } + if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) { + LOGE("GetAuthMgrByMessage, logicalSessionId exists in logicalSessionId2TokenIdMap_."); + return nullptr; + } + logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; + } + if (InitAndRegisterAuthMgr(false, tokenId, curSession, logicalSessionId) != DM_OK) { + return nullptr; + } + } else { + if (logicalSessionId != 0) { + if (curSession->logicalSessionSet_.find(logicalSessionId) == curSession->logicalSessionSet_.end()) { + LOGE("GetAuthMgrByMessage, The logical session ID does not exist in the physical session."); + return nullptr; + } + tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; + } + } + + return GetAuthMgrByTokenId(tokenId); +} + +int32_t DeviceManagerServiceImpl::TransferSrcOldAuthMgr(std::shared_ptr curSession) +{ + // New Old Receive 90, destroy new authMgr, create old authMgr, source side + // The old protocol has only one session, reverse lookup logicalSessionId and tokenId + int sessionId = curSession->sessionId_; + int64_t logicalSessionId = 0; + uint64_t tokenId = 0; + for (auto& pair : logicalSessionId2SessionIdMap_) { + if (pair.second == sessionId) { + logicalSessionId = pair.first; + tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; + } + } + if (logicalSessionId == 0 || tokenId == 0) { + LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr can not find logicalSessionId and tokenId."); + return ERR_DM_AUTH_FAILED; + } + std::string pkgName; + PeerTargetId peerTargetId; + std::map bindParam; + auto authMgr = GetAuthMgrByTokenId(tokenId); + authMgr->GetBindTargetParams(pkgName, peerTargetId, bindParam); + authMgr = nullptr; + authMgrMap_.erase(tokenId); + if (InitAndRegisterAuthMgr(false, tokenId, curSession, logicalSessionId) != DM_OK) { + return ERR_DM_AUTH_FAILED; + } + // send stop message + // Cannot stop using the new protocol. The new protocol is a signal mechanism and cannot be stopped serially. + // There will be a delay, causing new objects to be created before the stop is complete. + // Then the timeout mechanism of the new protocol will stop SoftBus again. + std::string endMessage = CreateTerminateMessage(); + (void)softbusConnector_->GetSoftbusSession()->SendData(sessionId, endMessage); + // Close new protocol session + CleanSessionMapByLogicalSessionId(logicalSessionId); + + if (authMgr_->BindTarget(pkgName, peerTargetId, bindParam, sessionId, 0) != DM_OK) { + LOGE("DeviceManagerServiceImpl::TransferSrcOldAuthMgr authManager BindTarget failed"); + return ERR_DM_AUTH_FAILED; + } + LOGI("DeviceManagerServiceImpl::TransferSrcOldAuthMgr src transfer to old version success"); + authMgr_->SetTransferReady(false); + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::TransferSinkOldAuthMgr(const JsonObject &jsonObject, + std::shared_ptr curSession) +{ + // Old New Received 80, New Old authMgr, Sink End + std::string bundleName; + if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { + bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); + } else if (jsonObject[TAG_BUNDLE_NAME].IsString()) { + bundleName = jsonObject[TAG_BUNDLE_NAME].Get(); + } else { + LOGE("DeviceManagerServiceImpl::TransferSinkOldAuthMgr can not find bundleName."); + return ERR_DM_AUTH_FAILED; + } + uint64_t tokenId = GetTokenId(false, -1, bundleName); + if (InitAndRegisterAuthMgr(false, tokenId, curSession, 0) != DM_OK) { + // Internal error log printing completed + return ERR_DM_AUTH_FAILED; + } + + // Parameter 2 sessionSide is 0, authMgr_ is empty, it must be the sink end. + // The src end will create the protocol object when BindTarget. + authMgr_->OnSessionOpened(curSession->sessionId_, 0, 0); + LOGI("DeviceManagerServiceImpl::TransferSinkOldAuthMgr sink transfer to old version success"); + authMgr_->SetTransferReady(false); + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::TransferOldAuthMgr(int32_t msgType, const JsonObject &jsonObject, + std::shared_ptr curSession) +{ + int ret = DM_OK; + if ((authMgr_ == nullptr || authMgr_->IsTransferReady()) && + (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE)) { + if (IsMessageOldVersion(jsonObject, curSession)) { + if (IsAuthManagerSourceByMessage(msgType)) { + ret = TransferSrcOldAuthMgr(curSession); + } else { + ret = TransferSinkOldAuthMgr(jsonObject, curSession); + } + } + } + + return ret; +} + + void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) { - SoftbusSession::OnBytesReceived(sessionId, data, dataLen); + if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > MAX_DATA_LEN) { + LOGE("[OnBytesReceived] Fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.", + sessionId, dataLen); + return; + } + + LOGI("start, sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); + + JsonObject jsonObject = GetJsonObjectFromData(data, dataLen); + if (jsonObject.IsDiscarded() || !jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { + LOGE("OnBytesReceived, MSG_TYPE parse failed."); + return; + } + int32_t msgType = jsonObject[TAG_MSG_TYPE].Get(); + int64_t logicalSessionId = 0; + if (jsonObject[DM_TAG_LOGICAL_SESSION_ID].IsNumberInteger()) { + logicalSessionId = jsonObject[DM_TAG_LOGICAL_SESSION_ID].Get(); + } + + std::shared_ptr curSession = GetCurSession(sessionId); + if (curSession == nullptr) { + LOGE("InitAndRegisterAuthMgr, The physical link is not created."); + return; + } + + std::shared_ptr authMgr = nullptr; + if (logicalSessionId != 0) { + authMgr = GetAuthMgrByMessage(msgType, logicalSessionId, jsonObject, curSession); + if (authMgr == nullptr) { + return; + } + } else { + /** +        Monitor old messages on ports 80/90 +        1. New-to-old: When the src side receives a 90 message and detects a version mismatch, it receives + the 90 message, destroys the current new authMgr, creates a new old protocol authMgr, and re-BindTarget. +        2. Old-to-new: When the sink side receives an 80 message and detects a version mismatch, it receives the 80 + message, directly creates a new old protocol authMgr, and re-OnSessionOpened and OnBytesReceived. +        */ + if (TransferOldAuthMgr(msgType, jsonObject, curSession) != DM_OK) { + LOGE("DeviceManagerServiceImpl::OnBytesReceived TransferOldAuthMgr failed"); + return; + } + + // Other messages, set the flag to true + if (authMgr_ && !authMgr_->IsTransferReady() && + !(msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE)) { + authMgr_->SetTransferReady(true); + } + authMgr = authMgr_; + } + + std::string message = std::string(reinterpret_cast(data), dataLen); + if (msgType == AUTH_DEVICE_REQ_NEGOTIATE || msgType == AUTH_DEVICE_RESP_NEGOTIATE) { + authMgr->OnAuthDeviceDataReceived(sessionId, message); + } else { + authMgr->OnDataReceived(sessionId, message); + } + return; } int32_t DeviceManagerServiceImpl::RequestCredential(const std::string &reqJsonStr, std::string &returnJsonStr) @@ -452,17 +1069,37 @@ int32_t DeviceManagerServiceImpl::UnRegisterCredentialCallback(const std::string return credentialMgr_->UnRegisterCredentialCallback(pkgName); } +static uint64_t GetSecondElement(const std::string& input) +{ + std::istringstream stream(input); + std::string token; + int count = 0; + uint64_t value = 0; + + while (std::getline(stream, token, ' ')) { + if (count >= 1) { + value = std::stoull(token); + break; + } + count++; + } + + return value; +} + int32_t DeviceManagerServiceImpl::RegisterUiStateCallback(const std::string &pkgName) { if (pkgName.empty()) { LOGE("RegisterUiStateCallback failed, pkgName is empty"); return ERR_DM_INPUT_PARA_INVALID; } - if (authMgr_ == nullptr) { + uint64_t tokenId = GetSecondElement(pkgName); + auto authMgr = GetAuthMgrByTokenId(tokenId); + if (authMgr == nullptr) { LOGE("authMgr_ is nullptr"); return ERR_DM_POINT_NULL; } - return authMgr_->RegisterUiStateCallback(pkgName); + return authMgr->RegisterUiStateCallback(pkgName); } int32_t DeviceManagerServiceImpl::UnRegisterUiStateCallback(const std::string &pkgName) @@ -471,11 +1108,13 @@ int32_t DeviceManagerServiceImpl::UnRegisterUiStateCallback(const std::string &p LOGE("UnRegisterUiStateCallback failed, pkgName is empty"); return ERR_DM_INPUT_PARA_INVALID; } - if (authMgr_ == nullptr) { + uint64_t tokenId = GetSecondElement(pkgName); + auto authMgr = GetAuthMgrByTokenId(tokenId); + if (authMgr == nullptr) { LOGE("authMgr_ is nullptr"); return ERR_DM_POINT_NULL; } - return authMgr_->UnRegisterUiStateCallback(pkgName); + return authMgr->UnRegisterUiStateCallback(pkgName); } int32_t DeviceManagerServiceImpl::PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject) @@ -565,6 +1204,15 @@ int32_t DeviceManagerServiceImpl::GetUdidHashByNetWorkId(const char *networkId, return DM_OK; } +std::shared_ptr DeviceManagerServiceImpl::GetConfigByTokenId() +{ + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + if (configsMap_.find(tokenId) == configsMap_.end()) { + configsMap_[tokenId] = std::make_shared(); + } + return configsMap_[tokenId]; +} + int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, const std::string &authCode) { if (pkgName.empty() || authCode.empty()) { @@ -572,25 +1220,294 @@ int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, con return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->ImportAuthCode(pkgName, authCode); + LOGI("DeviceManagerServiceImpl::ImportAuthCode pkgName is %{public}s, authCode is %{public}s", + pkgName.c_str(), authCode.c_str()); + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + auto config = GetConfigByTokenId(); + config->pkgName = pkgName; + config->authCode = authCode; // If registered multiple times, only the last one is kept + return DM_OK; + } + + return authMgr->ImportAuthCode(pkgName, authCode); } int32_t DeviceManagerServiceImpl::ExportAuthCode(std::string &authCode) { - int32_t ret = authMgr_->GeneratePincode(); + int32_t ret = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); authCode = std::to_string(ret); LOGI("ExportAuthCode success, authCode: %{public}s.", GetAnonyString(authCode).c_str()); return DM_OK; } +static JsonObject GetExtraJsonObject(const std::map &bindParam) +{ + std::string extra; + auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); + if (iter != bindParam.end()) { + extra = iter->second; + } else { + extra = ConvertMapToJsonString(bindParam); + } + + return JsonObject(extra); +} + +static int32_t GetHmlInfo(const JsonObject &jsonObject, bool &hmlEnable160M, int32_t &hmlActionId) +{ + if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBoolean()) { + hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get(); + LOGI("hmlEnable160M %{public}d", hmlEnable160M); + } + if (!IsString(jsonObject, PARAM_KEY_HML_ACTIONID)) { + LOGE("PARAM_KEY_HML_ACTIONID is not string"); + return ERR_DM_INPUT_PARA_INVALID; + } + std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); + if (!IsNumberString(actionIdStr)) { + LOGE("PARAM_KEY_HML_ACTIONID is not number"); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t actionId = std::atoi(actionIdStr.c_str()); + if (actionId <= 0) { + LOGE("PARAM_KEY_HML_ACTIONID is <= 0"); + return ERR_DM_INPUT_PARA_INVALID; + } + hmlActionId = actionId; + return DM_OK; +} + +static bool IsHmlSessionType(const JsonObject &jsonObject) +{ + std::string connSessionType; + if (jsonObject[PARAM_KEY_CONN_SESSIONTYPE].IsString()) { + connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); + LOGI("connSessionType %{public}s", connSessionType.c_str()); + } + return connSessionType == CONN_SESSION_TYPE_HML; +} + +int DeviceManagerServiceImpl::OpenAuthSession(const std::string& deviceId, + const std::map &bindParam) +{ + bool hmlEnable160M = false; + int32_t hmlActionId = 0; + JsonObject jsonObject = GetExtraJsonObject(bindParam); + if (jsonObject.IsDiscarded()) { + LOGE("extra string not a json type."); + return -1; + } + if (IsHmlSessionType(jsonObject)) { + auto ret = GetHmlInfo(jsonObject, hmlEnable160M, hmlActionId); + if (ret != DM_OK) { + LOGE("OpenAuthSession failed, GetHmlInfo failed."); + return ret; + } + LOGI("hmlActionId %{public}d, hmlEnable160M %{public}d", hmlActionId, hmlEnable160M); + return softbusConnector_->GetSoftbusSession()->OpenAuthSessionWithPara(deviceId, + hmlActionId, hmlEnable160M); + } else { + return softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); + } +} + +std::shared_ptr DeviceManagerServiceImpl::GetOrCreateSession(const std::string& deviceId, + const std::map &bindParam) +{ + std::shared_ptr instance; + int sessionId = -1; + // Acquire global lock to ensure thread safety for maps + { + std::lock_guard lock(mapMutex_); + if (deviceId2SessionIdMap_.find(deviceId) != deviceId2SessionIdMap_.end()) { + sessionId = deviceId2SessionIdMap_[deviceId]; + } + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + return sessionsMap_[sessionId]; + } + } + + // Get the lock corresponding to deviceId + std::mutex& device_mutex = deviceIdMutexMap_[deviceId]; + std::lock_guard lock(device_mutex); + + // Check again whether the corresponding object already exists (because other threads may have created it during + // the lock acquisition in the previous step) + { + std::lock_guard lock(mapMutex_); + if (deviceId2SessionIdMap_.find(deviceId) != deviceId2SessionIdMap_.end()) { + sessionId = deviceId2SessionIdMap_[deviceId]; + } + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + return sessionsMap_[sessionId]; + } + + sessionId = OpenAuthSession(deviceId, bindParam); + if (sessionId < 0) { + goto error; + } + + std::unique_lock cvLock(sessionEnableMutexMap_[sessionId]); + sessionEnableCvMap_[sessionId].wait(cvLock); + + instance = std::make_shared(sessionId, deviceId); + deviceId2SessionIdMap_[deviceId] = sessionId; + sessionsMap_[sessionId] = instance; + } + return instance; +error: + LOGE("OpenAuthSession failed, stop the authentication"); + return nullptr; +} + +int32_t DeviceManagerServiceImpl::GetDeviceInfo(const PeerTargetId &targetId, std::string &addrType, + std::string &deviceId, std::shared_ptr deviceInfo, int32_t &index) +{ + ConnectionAddr addr; + if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { + LOGI("parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); + if (!addrType.empty()) { + addr.type = static_cast(std::atoi(addrType.c_str())); + } else { + addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN; + } + if (memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length()) != 0) { + LOGE("get ip addr: %{public}s failed", GetAnonyString(targetId.wifiIp).c_str()); + return ERR_DM_SECURITY_FUNC_FAILED; + } + addr.info.ip.port = targetId.wifiPort; + deviceInfo->addr[index] = addr; + deviceId = targetId.wifiIp; + index++; + } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) { + LOGI("parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BR; + if (memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length()) != 0) { + LOGE("get brMac addr: %{public}s failed", GetAnonyString(targetId.brMac).c_str()); + return ERR_DM_SECURITY_FUNC_FAILED; + } + deviceInfo->addr[index] = addr; + deviceId = targetId.brMac; + index++; + } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) { + LOGI("parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE; + if (memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length()) != 0) { + LOGE("get bleMac addr: %{public}s failed", GetAnonyString(targetId.bleMac).c_str()); + return ERR_DM_SECURITY_FUNC_FAILED; + } + if (!targetId.deviceId.empty()) { + Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN, + targetId.deviceId.c_str(), targetId.deviceId.length()); + } + deviceInfo->addr[index] = addr; + deviceId = targetId.bleMac; + index++; + } else { + LOGE("DeviceManagerServiceImpl::GetDeviceInfo failed, not addr."); + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +bool DeviceManagerServiceImpl::IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid, + int32_t tokenId, int32_t userId) +{ + std::string extraInfo = DeviceProfileConnector::GetInstance().IsAuthNewVersion( + bindLevel, localUdid, remoteUdid, tokenId, userId); + JsonObject extraInfoJson(extraInfo); + if (extraInfoJson.IsDiscarded()) { + LOGE("IsAuthNewVersion extraInfoJson error"); + return false; + } + if (!extraInfoJson[TAG_DMVERSION].IsString()) { + LOGE("IsAuthNewVersion PARAM_KEY_OS_VERSION error"); + return false; + } + std::string dmVersion = extraInfoJson[TAG_DMVERSION].Get(); + if (CompareVersion(dmVersion, std::string(DM_VERSION_5_1_0)) || dmVersion == std::string(DM_VERSION_5_1_0)) { + return true; + } + return false; +} + +int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, + const std::map &bindParam) +{ + std::string addrType; + if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { + addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); + } + + std::shared_ptr deviceInfo = std::make_shared(); + int32_t index = 0; + int32_t ret = GetDeviceInfo(targetId, addrType, deviceId, deviceInfo, index); + if (ret != DM_OK) { + LOGE("GetDeviceInfo failed, ret: %{public}d", ret); + } + deviceInfo->addrNum = static_cast(index); + if (softbusConnector_->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) { + LOGE("DeviceManagerServiceImpl::ParseConnectAddr failed, AddMemberToDiscoverMap failed."); + return ERR_DM_INPUT_PARA_INVALID; + } + deviceInfo = nullptr; + return DM_OK; +} + int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &bindParam) { + int32_t ret = DM_OK; if (pkgName.empty()) { - LOGE("BindTarget failed, pkgName is empty"); + LOGE("BindTarget failed, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->BindTarget(pkgName, targetId, bindParam); + + std::string deviceId = ""; + PeerTargetId targetIdTmp = const_cast(targetId); + ret = ParseConnectAddr(targetId, deviceId, bindParam); + if (ret == DM_OK) { + targetIdTmp.deviceId = deviceId; + } else { + if (targetId.deviceId.empty()) { + LOGE("DeviceManagerServiceImpl::BindTarget failed, ParseConnectAddr failed."); + return ERR_DM_INPUT_PARA_INVALID; + } + } + // Created only at the source end. The same target device will not be created repeatedly with the new protocol. + std::shared_ptr curSession = GetOrCreateSession(targetIdTmp.deviceId, bindParam); + if (curSession == nullptr) { + LOGE("Failed to create the session. Target deviceId: %{public}s.", targetIdTmp.deviceId.c_str()); + return ERR_DM_AUTH_OPEN_SESSION_FAILED; + } + + // Logical session random number + int sessionId = curSession->sessionId_; + int64_t logicalSessionId = GenerateRandNum(sessionId); + if (curSession->logicalSessionSet_.find(logicalSessionId) != curSession->logicalSessionSet_.end()) { + LOGE("Failed to create the logical session."); + return ERR_DM_LOGIC_SESSION_CREATE_FAILED; + } + + // Create on the src end. + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + ret = InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId); + if (ret != DM_OK) { + return ret; + } + curSession->logicalSessionSet_.insert(logicalSessionId); + curSession->logicalSessionCnt_.fetch_add(1); + logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; + logicalSessionId2SessionIdMap_[logicalSessionId] = sessionId; + + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr is nullptr"); + return ERR_DM_POINT_NULL; + } + authMgr->SetBindTargetParams(targetId); + return authMgr->BindTarget(pkgName, targetIdTmp, bindParam, sessionId, logicalSessionId); } int32_t DeviceManagerServiceImpl::DpAclAdd(const std::string &udid) @@ -712,12 +1629,13 @@ void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEvent { if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) { LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback on screen locked."); - if (authMgr_ != nullptr) { - authMgr_->OnScreenLocked(); - return; - } else { - LOGE("authMgr_ is null, cannot call OnScreenLocked."); + for (auto& pair : authMgrMap_) { + if (pair.second != nullptr) { + LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback tokenId: %{public}" PRId64 ".", pair.first); + pair.second->OnScreenLocked(); + } } + return; } LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback error."); } @@ -749,8 +1667,9 @@ void DeviceManagerServiceImpl::HandleDeviceNotTrust(const std::string &udid) LOGE("HandleDeviceNotTrust udid is empty."); return; } - CHECK_NULL_VOID(authMgr_); - authMgr_->HandleDeviceNotTrust(udid); + DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid); + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroupByUdid(udid); } int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const std::string &localUdid, @@ -822,18 +1741,48 @@ DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) return authForm; } +int32_t DeviceManagerServiceImpl::DeleteGroup(const std::string &pkgName, const std::string &deviceId) +{ + LOGI("DeviceManagerServiceImpl::DeleteGroup"); + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_FAILED; + } + std::vector groupList; + CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); + hiChainConnector_->GetRelatedGroups(deviceId, groupList); + for (const auto &item : groupList) { + std::string groupId = item.groupId; + hiChainConnector_->DeleteGroup(groupId); + } + return DM_OK; +} + void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid) { char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); - int32_t bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + DmOfflineParam offlineParam; + int32_t bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent( + remoteUserId, remoteUdid, localUdid, offlineParam); if (static_cast(bindType) == DM_INVALIED_BINDTYPE) { LOGE("Invalied bindtype."); return; } - CHECK_NULL_VOID(authMgr_); - authMgr_->DeleteGroup(DM_PKG_NAME, remoteUdid); + int32_t userId = 0; + MultipleUserConnector::GetCallerUserId(userId); + bool isNewVersion = IsAuthNewVersion(USER, localUdid, remoteUdid, 0, userId); + if (!isNewVersion) { + DeleteGroup(DM_PKG_NAME, remoteUdid); + return; + } + for (auto skId : offlineParam.skIdVec) { + DeviceProfileConnector::GetInstance().DeleteSessionKey(skId); + } + for (auto credId : offlineParam.credIdVec) { + hiChainAuthConnector_->DeleteCredential(userId, credId); + } } void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, @@ -842,15 +1791,20 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); - ProcessInfo processInfo = + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); - if (processInfo.pkgName.empty()) { - LOGE("Pkgname is empty."); - return; - } + int32_t userId = 0; + MultipleUserConnector::GetCallerUserId(userId); CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetProcessInfo(processInfo); + CHECK_NULL_VOID(hiChainAuthConnector_); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); softbusConnector_->HandleDeviceOffline(remoteUdid); + for (auto skId : offlineParam.skIdVec) { + DeviceProfileConnector::GetInstance().DeleteSessionKey(skId); + } + for (auto credId : offlineParam.credIdVec) { + hiChainAuthConnector_->DeleteCredential(userId, credId); + } } void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, @@ -860,16 +1814,43 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); - ProcessInfo processInfo = + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, peerTokenId); - if (processInfo.pkgName.empty()) { - LOGE("Pkgname is empty."); - return; + int32_t userId = 0; + MultipleUserConnector::GetCallerUserId(userId); + CHECK_NULL_VOID(softbusConnector_); + CHECK_NULL_VOID(hiChainAuthConnector_); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + for (auto skId : offlineParam.skIdVec) { + DeviceProfileConnector::GetInstance().DeleteSessionKey(skId); + } + for (auto credId : offlineParam.credIdVec) { + hiChainAuthConnector_->DeleteCredential(userId, credId); } +} + +void DeviceManagerServiceImpl::HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId) +{ + LOGI("HandleServiceUnBindEvent remoteTokenId = %{public}d, userId: %{public}d, remoteUdid: %{public}s.", + remoteTokenId, userId, GetAnonyString(remoteUdid).c_str()); + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleServiceUnBindEvent( + userId, remoteUdid, localUdid, remoteTokenId); CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetProcessInfo(processInfo); + CHECK_NULL_VOID(hiChainAuthConnector_); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); softbusConnector_->HandleDeviceOffline(remoteUdid); + for (auto skId : offlineParam.skIdVec) { + DeviceProfileConnector::GetInstance().DeleteSessionKey(skId); + } + for (auto credId : offlineParam.credIdVec) { + hiChainAuthConnector_->DeleteCredential(userId, credId); + } } void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector &foregroundUserIds, @@ -962,7 +1943,7 @@ int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, i } DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.GetAccessControlId()); listener_->OnAppUnintall(item.GetAccesser().GetAccesserBundleName()); - if (item.GetBindLevel() == DEVICE) { + if (item.GetBindLevel() == USER) { userIdVec.push_back(item.GetAccesser().GetAccesserUserId()); delACLInfoVec.push_back(std::pair(item.GetAccesser().GetAccesserUserId(), item.GetAccessee().GetAccesseeDeviceId())); @@ -1008,8 +1989,13 @@ void DeviceManagerServiceImpl::HandleDeviceUnBind(int32_t bindType, const std::s int32_t DeviceManagerServiceImpl::RegisterAuthenticationType(int32_t authenticationType) { - CHECK_NULL_RETURN(authMgr_, ERR_DM_POINT_NULL); - return authMgr_->RegisterAuthenticationType(authenticationType); + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + auto config = GetConfigByTokenId(); + config->authenticationType = authenticationType; // only the last registration is retained + return DM_OK; + } + return authMgr->RegisterAuthenticationType(authenticationType); } void DeviceManagerServiceImpl::DeleteAlwaysAllowTimeOut() @@ -1059,6 +2045,74 @@ int32_t DeviceManagerServiceImpl::CheckDeviceInfoPermission(const std::string &l return DM_OK; } +int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &pkgName, const std::string &localUdid, + const std::string &remoteUdid, int32_t bindLevel, const std::string &extra) +{ + LOGI("DeleteAcl pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", + pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); + DmOfflineParam offlineParam = + DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localUdid, remoteUdid, bindLevel, extra); + if (offlineParam.bindType == INVALIED_TYPE) { + LOGE("Acl not contain the pkgname bind data."); + return ERR_DM_FAILED; + } + if (static_cast(bindLevel) == APP) { + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + if (offlineParam.leftAclNumber != 0) { + LOGI("The pkgName unbind app-level type leftAclNumber not zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + return DM_OK; + } + if (offlineParam.leftAclNumber == 0) { + LOGI("The pkgName unbind app-level type leftAclNumber is zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + return DM_OK; + } + } + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber != 0) { + LOGI("Unbind deivce-level, retain identical account bind type."); + return DM_OK; + } + if (static_cast(bindLevel) == USER && offlineParam.leftAclNumber == 0) { + LOGI("Unbind deivce-level, retain null."); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + return DM_OK; + } + return ERR_DM_FAILED; +} + +int32_t DeviceManagerServiceImpl::DeleteAclV2(const std::string &sessionName, const std::string &localUdid, + const std::string &remoteUdid, int32_t bindLevel, const std::string &extra) +{ + LOGI("DeleteAclV2 sessionName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", + sessionName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); + uint32_t tokenId = 0; + MultipleUserConnector::GetTokenId(tokenId); + int32_t userId = 0; + MultipleUserConnector::GetCallerUserId(userId); + bool isNewVersion = IsAuthNewVersion(bindLevel, localUdid, remoteUdid, tokenId, userId); + if (!isNewVersion) { + return DeleteAcl(sessionName, localUdid, remoteUdid, bindLevel, extra); + } + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().DeleteAccessControlListV2( + tokenId, localUdid, remoteUdid, bindLevel, extra); + if (offlineParam.bindType == INVALIED_TYPE) { + LOGE("Acl not contain the sessionName bind data."); + return ERR_DM_FAILED; + } + for (auto skId : offlineParam.skIdVec) { + DeviceProfileConnector::GetInstance().DeleteSessionKey(skId); + } + for (auto credId : offlineParam.credIdVec) { + hiChainAuthConnector_->DeleteCredential(userId, credId); + } + return ERR_DM_FAILED; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index f82b8f95f..e8ac3281e 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -613,6 +613,15 @@ int32_t DeviceManagerServiceImpl::CheckDeviceInfoPermission(const std::string &l return DM_OK; } +void DeviceManagerServiceImpl::HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId) +{ + (void)userId; + (void)remoteUdid; + (void)remoteTokenId; + return; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 8ba83a8ad..fcccfc92b 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -260,6 +260,8 @@ public: virtual void DeleteAlwaysAllowTimeOut() = 0; virtual void CheckDeleteCredential(const std::string &remoteUdid) = 0; virtual int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId) = 0; + virtual void HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h index 227a5caf5..641f333c6 100644 --- a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h +++ b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h @@ -69,6 +69,7 @@ struct RelationShipChangeMsg { void ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const; void ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; void ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; + void ToServiceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; bool ToSyncFrontOrBackUserIdPayLoad(uint8_t *&msg, uint32_t &len) const; void ToDelUserPayLoad(uint8_t *&msg, uint32_t &len) const; void ToStopUserPayLoad(uint8_t *&msg, uint32_t &len) const; @@ -77,6 +78,7 @@ struct RelationShipChangeMsg { bool FromAccountLogoutPayLoad(const cJSON *payloadJson); bool FromDeviceUnbindPayLoad(const cJSON *payloadJson); bool FromAppUnbindPayLoad(const cJSON *payloadJson); + bool FromServiceUnbindPayLoad(const cJSON *payloadJson); bool FromSyncFrontOrBackUserIdPayLoad(const cJSON *payloadJson); bool FromDelUserPayLoad(const cJSON *payloadJson); bool FromStopUserPayLoad(const cJSON *payloadJson); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 335fdfa9e..4ca6cfee4 100644 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2419,7 +2419,7 @@ void DeviceManagerService::SendUnBindBroadCast(const std::vector &p uint64_t tokenId, int32_t bindLevel) { LOGI("TokenId %{public}" PRId64", bindLevel %{public}d, userId %{public}d.", tokenId, bindLevel, userId); - if (static_cast(bindLevel) == DEVICE) { + if (static_cast(bindLevel) == USER) { SendDeviceUnBindBroadCast(peerUdids, userId); return; } @@ -2436,7 +2436,7 @@ void DeviceManagerService::SendUnBindBroadCast(const std::vector &p void DeviceManagerService::SendUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId, int32_t bindLevel, uint64_t peerTokenId) { - if (static_cast(bindLevel) == DEVICE) { + if (static_cast(bindLevel) == USER) { SendDeviceUnBindBroadCast(peerUdids, userId); return; } @@ -2532,6 +2532,10 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) static_cast(relationShipMsg.tokenId)); } break; + case RelationShipChangeType::SERVICE_UNBIND: + dmServiceImpl_->HandleServiceUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid, + static_cast(relationShipMsg.tokenId)); + break; case RelationShipChangeType::SYNC_USERID: HandleUserIdsBroadCast(relationShipMsg.userIdInfos, relationShipMsg.peerUdid, relationShipMsg.syncUserIdFlag); diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index 962391c13..ce38f2ade 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -116,6 +116,10 @@ bool RelationShipChangeMsg::ToBroadcastPayLoad(uint8_t *&msg, uint32_t &len) con ToAppUnbindPayLoad(msg, len); ret = true; break; + case RelationShipChangeType::SERVICE_UNBIND: + ToServiceUnbindPayLoad(msg, len); + ret = true; + break; case RelationShipChangeType::SYNC_USERID: ret = ToSyncFrontOrBackUserIdPayLoad(msg, len); break; @@ -152,6 +156,9 @@ bool RelationShipChangeMsg::FromBroadcastPayLoad(const cJSON *payloadJson, Relat case RelationShipChangeType::APP_UNBIND: ret = FromAppUnbindPayLoad(payloadJson); break; + case RelationShipChangeType::SERVICE_UNBIND: + ret = FromServiceUnbindPayLoad(payloadJson); + break; case RelationShipChangeType::SYNC_USERID: ret = FromSyncFrontOrBackUserIdPayLoad(payloadJson); break; @@ -188,6 +195,8 @@ bool RelationShipChangeMsg::IsValid() const ret = (userId != UINT32_MAX); break; case RelationShipChangeType::SERVICE_UNBIND: + ret = (userId != UINT32_MAX); + break; case RelationShipChangeType::APP_UNINSTALL: // current NOT support ret = false; @@ -210,7 +219,8 @@ bool RelationShipChangeMsg::IsChangeTypeValid() { return (type == RelationShipChangeType::ACCOUNT_LOGOUT) || (type == RelationShipChangeType::DEVICE_UNBIND) || (type == RelationShipChangeType::APP_UNBIND) || (type == RelationShipChangeType::SYNC_USERID) || - (type == RelationShipChangeType::DEL_USER) || (type == RelationShipChangeType::STOP_USER); + (type == RelationShipChangeType::DEL_USER) || (type == RelationShipChangeType::STOP_USER) || + (type == RelationShipChangeType::SERVICE_UNBIND); } bool RelationShipChangeMsg::IsChangeTypeValid(uint32_t type) @@ -220,7 +230,8 @@ bool RelationShipChangeMsg::IsChangeTypeValid(uint32_t type) (type == (uint32_t)RelationShipChangeType::APP_UNBIND) || (type == (uint32_t)RelationShipChangeType::SYNC_USERID) || (type == (uint32_t)RelationShipChangeType::DEL_USER) || - (type == (uint32_t)RelationShipChangeType::STOP_USER); + (type == (uint32_t)RelationShipChangeType::STOP_USER) || + (type == (uint32_t)RelationShipChangeType::SERVICE_UNBIND); } void RelationShipChangeMsg::ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const @@ -263,6 +274,11 @@ void RelationShipChangeMsg::ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) con len = APP_UNBIND_PAYLOAD_LEN; } +void RelationShipChangeMsg::ToServiceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const +{ + ToAppUnbindPayLoad(msg, len); +} + bool RelationShipChangeMsg::ToSyncFrontOrBackUserIdPayLoad(uint8_t *&msg, uint32_t &len) const { uint32_t userIdNum = static_cast(userIdInfos.size()); @@ -407,6 +423,11 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) return true; } +bool RelationShipChangeMsg::FromServiceUnbindPayLoad(const cJSON *payloadJson) +{ + return FromAppUnbindPayLoad(payloadJson); +} + bool RelationShipChangeMsg::FromSyncFrontOrBackUserIdPayLoad(const cJSON *payloadJson) { if (payloadJson == NULL) { -- Gitee From d601053c02eae8cb68b999626503c8b3cf2cb4ef Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sun, 6 Apr 2025 11:54:44 +0800 Subject: [PATCH 2/8] add test code Signed-off-by: hwzhangchuang --- test/commonfuzztest/BUILD.gn | 2 + .../dm_auth_manager_fuzzer.cpp | 3 +- .../dmauthmanagerv2_fuzzer/BUILD.gn | 79 ++ .../dmauthmanagerv2_fuzzer/corpus/init | 13 + .../dm_auth_manager_fuzzer.cpp | 122 +++ .../dm_auth_manager_fuzzer.h | 21 + .../dmauthmanagerv2_fuzzer/project.xml | 25 + .../ondatareceivedv2_fuzzer/BUILD.gn | 78 ++ .../ondatareceivedv2_fuzzer/corpus/init | 13 + .../on_data_received_fuzzer.cpp | 71 ++ .../on_data_received_fuzzer.h | 21 + .../ondatareceivedv2_fuzzer/project.xml | 25 + .../UTTest_dm_auth_manager_first.cpp | 17 +- .../UTTest_dm_auth_manager_second.cpp | 24 +- .../UTTest_dm_auth_manager_third.cpp | 2 +- .../UTTest_dm_deviceprofile_connector.cpp | 74 +- ...Test_dm_deviceprofile_connector_second.cpp | 4 +- .../UTTest_hichain_auth_connector.cpp | 30 +- .../UTTest_hichain_auth_connector.h | 3 +- .../on_bytes_received_fuzzer.cpp | 2 - .../softbus_session_fuzzer.cpp | 1 - .../softbus_session_object_fuzzer.cpp | 13 - .../UTTest_softbus_connector.cpp | 12 +- .../UTTest_softbus_session.cpp | 7 +- test/unittest/BUILD.gn | 33 +- .../unittest/UTTest_auth_credential_state.cpp | 764 ++++++++++++++++++ test/unittest/UTTest_auth_credential_state.h | 50 ++ test/unittest/UTTest_auth_negotiate_state.cpp | 141 ++++ test/unittest/UTTest_auth_negotiate_state.h | 48 ++ test/unittest/UTTest_auth_pin_auth_state.cpp | 412 ++++++++++ test/unittest/UTTest_auth_pin_auth_state.h | 45 ++ .../UTTest_device_manager_service.cpp | 2 +- .../UTTest_device_manager_service_impl.cpp | 26 +- .../mock/deviceprofile_connector_mock.cpp | 8 +- .../mock/deviceprofile_connector_mock.h | 12 +- .../mock/dm_auth_message_processor_mock.cpp | 27 + .../mock/dm_auth_message_processor_mock.h | 34 + .../mock/dm_auth_state_machine_mock.cpp | 27 + .../mock/dm_auth_state_machine_mock.h | 33 + .../mock/hichain_auth_connector_mock.cpp | 38 + .../mock/hichain_auth_connector_mock.h | 18 + .../unittest/mock/os_account_manager_mock.cpp | 5 + test/unittest/mock/os_account_manager_mock.h | 2 + test/unittest/mock/softbus_connector_mock.cpp | 5 + test/unittest/mock/softbus_connector_mock.h | 2 + test/unittest/mock/softbus_session_mock.cpp | 15 + test/unittest/mock/softbus_session_mock.h | 7 + 47 files changed, 2281 insertions(+), 135 deletions(-) create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/BUILD.gn create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/corpus/init create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.h create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/project.xml create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/BUILD.gn create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/corpus/init create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.h create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/project.xml create mode 100644 test/unittest/UTTest_auth_credential_state.cpp create mode 100644 test/unittest/UTTest_auth_credential_state.h create mode 100644 test/unittest/UTTest_auth_negotiate_state.cpp create mode 100644 test/unittest/UTTest_auth_negotiate_state.h create mode 100644 test/unittest/UTTest_auth_pin_auth_state.cpp create mode 100644 test/unittest/UTTest_auth_pin_auth_state.h create mode 100644 test/unittest/mock/dm_auth_message_processor_mock.cpp create mode 100644 test/unittest/mock/dm_auth_message_processor_mock.h create mode 100644 test/unittest/mock/dm_auth_state_machine_mock.cpp create mode 100644 test/unittest/mock/dm_auth_state_machine_mock.h diff --git a/test/commonfuzztest/BUILD.gn b/test/commonfuzztest/BUILD.gn index 4430b898c..c88c67ba2 100644 --- a/test/commonfuzztest/BUILD.gn +++ b/test/commonfuzztest/BUILD.gn @@ -19,12 +19,14 @@ group("fuzztest") { "authenticatedeviceservice_fuzzer:fuzztest", "authenticatedeviceserviceimpl_fuzzer:fuzztest", "dmauthmanager_fuzzer:fuzztest", + "dmauthmanagerv2_fuzzer:fuzztest", "dmcommoneventmanager_fuzzer:fuzztest", "dmcredentialimpl_fuzzer:fuzztest", "generateencrypteduuid_fuzzer:fuzztest", "getdeviceinfo_fuzzer:fuzztest", "hichainconnector_fuzzer:fuzztest", "ondatareceived_fuzzer:fuzztest", + "ondatareceivedv2_fuzzer:fuzztest", "onerror_fuzzer:fuzztest", "onfinish_fuzzer:fuzztest", "onrequest_fuzzer:fuzztest", diff --git a/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp b/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp index 2e0da79a6..fc9ff5b79 100644 --- a/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp +++ b/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp @@ -46,6 +46,7 @@ int32_t g_pageId = 1; int32_t g_reason = 1; int32_t g_state = 1; int64_t g_requestId = 1; +int64_t g_localSessionId = 1; std::map g_bindParam; @@ -80,7 +81,7 @@ void DmAuthManagerFuzzTest(const uint8_t* data, size_t size) g_authManager->OnSessionOpened(g_sessionId, g_sessionSide, g_result); g_authManager->AuthenticateDevice(str, g_authType, str, str); g_authManager->ImportAuthCode(str, str); - g_authManager->BindTarget(str, g_targetId, g_bindParam); + g_authManager->BindTarget(str, g_targetId, g_bindParam, g_sessionId, g_localSessionId); g_authManager->ShowConfigDialog(); g_authManager->ShowAuthInfoDialog(); g_authManager->ShowStartAuthDialog(); diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/BUILD.gn b/test/commonfuzztest/dmauthmanagerv2_fuzzer/BUILD.gn new file mode 100644 index 000000000..d81bcb502 --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/BUILD.gn @@ -0,0 +1,79 @@ +# Copyright (c) 2023-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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("//foundation/distributedhardware/device_manager/device_manager.gni") + +##############################fuzztest########################################## +ohos_fuzztest("DmAuthManagerV2FuzzTest") { + module_out_path = fuzz_test_output_path + fuzz_config_file = + "${devicemanager_path}/test/commonfuzztest/dmauthmanagerv2_fuzzer" + + include_dirs = [ + "${innerkits_path}/native_cpp/include", + "${servicesimpl_path}/include/ability", + "${servicesimpl_path}/include/adapter", + "${servicesimpl_path}/include/authentication_v2", + "${servicesimpl_path}/include/dependency/hichain", + "${servicesimpl_path}/include/dependency/softbus", + "${servicesimpl_path}/include/dependency/timer", + ] + + cflags = [ + "-g", + "-O0", + "-Dprivate=public", + "-Dprotected=public", + "-Werror", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "dm_auth_manager_fuzzer.cpp" ] + + deps = [ + "${innerkits_path}/native_cpp:devicemanagersdk", + "${services_path}:devicemanagerservice", + "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", + ] + + external_deps = [ + "device_auth:deviceauth_sdk", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "cJSON:cjson", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"DmAuthManagerV2FuzzTest\"", + "LOG_DOMAIN=0xD004110", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":DmAuthManagerV2FuzzTest" ] +} +############################################################################### diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/corpus/init b/test/commonfuzztest/dmauthmanagerv2_fuzzer/corpus/init new file mode 100644 index 000000000..d9719cafa --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# Copyright (c) 2023 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. +FUZZ \ No newline at end of file diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp new file mode 100644 index 000000000..0858f3b67 --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2025-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 +#include +#include "device_manager_service_listener.h" +#include "auth_manager.h" +#include "dm_auth_manager_fuzzer.h" + +namespace OHOS { +namespace DistributedHardware { + +int32_t g_sessionId = 1; +int32_t g_sessionSide = 0; +int32_t g_result = 1; +int32_t g_authType = 1; +int32_t g_status = 1; +int32_t g_pinCode = 1; +int32_t g_action = 1; +int32_t g_userId = 1; +int32_t g_pageId = 1; +int32_t g_reason = 1; +int32_t g_state = 1; +int64_t g_requestId = 1; +int64_t g_operationCode = 1; +int64_t g_localSessionId = 1; + +std::map g_bindParam; + +PeerTargetId g_targetId = { + .deviceId = "deviceId", + .brMac = "brMac", + .bleMac = "bleMac", + .wifiIp = "wifiIp", +}; + +// AuthSrcManager fuzz +void DmAuthSrcManagerFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + FuzzedDataProvider fdp(data, size); + std::string str(reinterpret_cast(data), size); + int32_t bindLevel = fdp.ConsumeIntegral(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + + authManager->OnUserOperation(g_action, str); + authManager->BindTarget(str, g_targetId, g_bindParam, g_sessionId, g_localSessionId); + authManager->StopAuthenticateDevice(str); + authManager->ImportAuthCode(str, str); + authManager->RegisterUiStateCallback(str); + authManager->UnRegisterUiStateCallback(str); + authManager->UnAuthenticateDevice(str, str, bindLevel); + authManager->UnBindDevice(str, str, bindLevel, str); + authManager->HandleDeviceNotTrust(str); + authManager->DeleteGroup(str, str); + authManager->AuthDeviceTransmit(g_requestId, data, size); + authManager->AuthDeviceSessionKey(g_requestId, data, size); + authManager->AuthDeviceRequest(g_requestId, g_operationCode, str.c_str()); + authManager->OnDataReceived(g_sessionId, str); + authManager->OnAuthDeviceDataReceived(g_sessionId, str); +} + +// AuthSinkManager fuzz +void DmAuthSinkManagerFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + FuzzedDataProvider fdp(data, size); + std::string str(reinterpret_cast(data), size); + int32_t bindLevel = fdp.ConsumeIntegral(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + + authManager->OnUserOperation(g_action, str); + authManager->BindTarget(str, g_targetId, g_bindParam, g_sessionId, g_localSessionId); + authManager->StopAuthenticateDevice(str); + authManager->ImportAuthCode(str, str); + authManager->RegisterUiStateCallback(str); + authManager->UnRegisterUiStateCallback(str); + authManager->UnAuthenticateDevice(str, str, bindLevel); + authManager->UnBindDevice(str, str, bindLevel, str); + authManager->HandleDeviceNotTrust(str); + authManager->DeleteGroup(str, str); + authManager->AuthDeviceTransmit(g_requestId, data, size); + authManager->AuthDeviceSessionKey(g_requestId, data, size); + authManager->AuthDeviceRequest(g_requestId, g_operationCode, str.c_str()); + authManager->OnDataReceived(g_sessionId, str); + authManager->OnAuthDeviceDataReceived(g_sessionId, str); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::DmAuthSrcManagerFuzzTest(data, size); + OHOS::DistributedHardware::DmAuthSinkManagerFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.h b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.h new file mode 100644 index 000000000..35643d1c4 --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 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. + */ + +#ifndef DM_AUTH_MANAGER_FUZZER_H +#define DM_AUTH_MANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "dmauthmanagerv2_fuzzer" + +#endif // DM_AUTH_MANAGER_FUZZER_H \ No newline at end of file diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/project.xml b/test/commonfuzztest/dmauthmanagerv2_fuzzer/project.xml new file mode 100644 index 000000000..bac4974e9 --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/BUILD.gn b/test/commonfuzztest/ondatareceivedv2_fuzzer/BUILD.gn new file mode 100644 index 000000000..6ecb86c33 --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/BUILD.gn @@ -0,0 +1,78 @@ +# Copyright (c) 2023-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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("//foundation/distributedhardware/device_manager/device_manager.gni") + +##############################fuzztest########################################## +ohos_fuzztest("OnDataReceivedV2FuzzTest") { + module_out_path = fuzz_test_output_path + fuzz_config_file = + "${devicemanager_path}/test/commonfuzztest/ondatareceivedv2_fuzzer" + + include_dirs = [ + "${innerkits_path}/native_cpp/include", + "${servicesimpl_path}/include/ability", + "${servicesimpl_path}/include/adapter", + "${servicesimpl_path}/include/authentication", + "${servicesimpl_path}/include/dependency/hichain", + "${servicesimpl_path}/include/dependency/softbus", + "${servicesimpl_path}/include/dependency/timer", + ] + + cflags = [ + "-g", + "-O0", + "-Dprivate=public", + "-Dprotected=public", + "-Werror", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "on_data_received_fuzzer.cpp" ] + + deps = [ + "${services_path}:devicemanagerservice", + "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", + ] + + external_deps = [ + "device_auth:deviceauth_sdk", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "cJSON:cjson", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"OnDataReceivedV2FuzzTest\"", + "LOG_DOMAIN=0xD004110", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":OnDataReceivedV2FuzzTest" ] +} +############################################################################### diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/corpus/init b/test/commonfuzztest/ondatareceivedv2_fuzzer/corpus/init new file mode 100644 index 000000000..d9719cafa --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# Copyright (c) 2023 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. +FUZZ \ No newline at end of file diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp new file mode 100644 index 000000000..6b1cec0cc --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2023-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 +#include +#include "auth_manager.h" +#include "device_manager_service_listener.h" +#include "on_data_received_fuzzer.h" + +namespace OHOS { +namespace DistributedHardware { +// AuthSrcManager fuzz +void OnDataReceivedSrcFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + FuzzedDataProvider fdp(data, size); + int32_t sessionId = fdp.ConsumeIntegral(); + std::string message(reinterpret_cast(data), size); + authManager->OnDataReceived(sessionId, message); + authManager->OnSessionClosed(sessionId); +} + +// AuthSinkManager fuzz +void OnDataReceivedSinkFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + FuzzedDataProvider fdp(data, size); + int32_t sessionId = fdp.ConsumeIntegral(); + std::string message(reinterpret_cast(data), size); + authManager->OnDataReceived(sessionId, message); + authManager->OnSessionClosed(sessionId); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::OnDataReceivedSrcFuzzTest(data, size); + OHOS::DistributedHardware::OnDataReceivedSinkFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.h b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.h new file mode 100644 index 000000000..e59b91fda --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2023 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 ON_DATA_RECEIVED_FUZZER_H +#define ON_DATA_RECEIVED_FUZZER_H + +#define FUZZ_PROJECT_NAME "ondatareceivedv2_fuzzer" + +#endif // ON_DATA_RECEIVED_FUZZER_H \ No newline at end of file diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/project.xml b/test/commonfuzztest/ondatareceivedv2_fuzzer/project.xml new file mode 100644 index 000000000..bac4974e9 --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 06a5ba958..c01281da1 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -203,7 +203,7 @@ HWTEST_F(DmAuthManagerTest, StartAuthProcess_001, testing::ext::TestSize.Level1) int32_t action = 0; g_reportAuthConfirmBoxReturnBoolValue = false; authManager_->remoteVersion_ = "4.1.5.2"; - authManager_->authResponseContext_->bindLevel = DEVICE; + authManager_->authResponseContext_->bindLevel = USER; int32_t ret = authManager_->StartAuthProcess(action); ASSERT_EQ(ret, DM_OK); } @@ -564,7 +564,7 @@ HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_001, testing::ext::TestSize.Lev { std::string pkgName; std::string udid = "UnAuthenticateDevice_001"; - int32_t bindLevel = DEVICE; + int32_t bindLevel = USER; int32_t ret = authManager_->UnAuthenticateDevice(pkgName, udid, bindLevel); EXPECT_NE(ret, DM_OK); @@ -594,7 +594,7 @@ HWTEST_F(DmAuthManagerTest, UnBindDevice_002, testing::ext::TestSize.Level1) { std::string pkgName; std::string udid = "UnBindDevice_002"; - int32_t bindLevel = DEVICE; + int32_t bindLevel = USER; std::string extra = "extraTest"; int32_t ret = authManager_->UnBindDevice(pkgName, udid, bindLevel, extra); EXPECT_NE(ret, DM_OK); @@ -1038,13 +1038,6 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceSessionKey001, testing::ext::TestSize.Leve authManager_->GetSessionKeyIdSync(requestId); } -HWTEST_F(DmAuthManagerTest, GetRemoteDeviceId001, testing::ext::TestSize.Level1) -{ - std::string deviceId; - authManager_->GetRemoteDeviceId(deviceId); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - HWTEST_F(DmAuthManagerTest, CompatiblePutAcl001, testing::ext::TestSize.Level1) { authManager_->authRequestState_ = std::make_shared(); @@ -1501,7 +1494,7 @@ HWTEST_F(DmAuthManagerTest, GetBindLevel_001, testing::ext::TestSize.Level1) EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(true)); int32_t ret = authManager_->GetBindLevel(bindLevel); - ASSERT_EQ(ret, DEVICE); + ASSERT_EQ(ret, USER); EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); ret = authManager_->GetBindLevel(bindLevel); @@ -1699,7 +1692,7 @@ HWTEST_F(DmAuthManagerTest, GetBinderInfo_001, testing::ext::TestSize.Level1) ret = authManager_->GetBinderInfo(); ASSERT_EQ(ret, DM_OK); - authManager_->authResponseContext_->bindLevel = DEVICE; + authManager_->authResponseContext_->bindLevel = USER; authManager_->SetProcessInfo(); authManager_->authResponseContext_->bindLevel = SERVICE; diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 23269a6cf..e1ebd3cfe 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -800,7 +800,7 @@ HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_004, testing::ext::TestSize.Leve authManager_->importPkgName_ = "hostPkgName"; authManager_->authResponseContext_->hostPkgName = "hostPkgName"; authManager_->remoteVersion_ = "4.1.5.2"; - authManager_->authResponseContext_->bindLevel = DEVICE; + authManager_->authResponseContext_->bindLevel = USER; authManager_->authResponseContext_->targetDeviceName = "ShowStartAuthDialog_004"; authManager_->ShowStartAuthDialog(); EXPECT_NE(authManager_->authResponseContext_->targetDeviceName, DmDialogManager::GetInstance().targetDeviceName_); @@ -847,7 +847,7 @@ HWTEST_F(DmAuthManagerTest, ProcessPincode_003, testing::ext::TestSize.Level1) authManager_->importPkgName_ = "hostPkgName"; authManager_->authResponseContext_->hostPkgName = "hostPkgName"; authManager_->remoteVersion_ = "4.1.5.2"; - authManager_->authResponseContext_->bindLevel = DEVICE; + authManager_->authResponseContext_->bindLevel = USER; authManager_->authResponseContext_->targetDeviceName = "ShowStartAuthDialog_004"; EXPECT_CALL(*hiChainAuthConnectorMock_, AuthDevice(_, _, _, _)).WillOnce(Return(DM_OK)); int32_t ret = authManager_->ProcessPincode(pinCode); @@ -915,7 +915,9 @@ HWTEST_F(DmAuthManagerTest, BindTarget_001, testing::ext::TestSize.Level1) std::string pkgName; PeerTargetId targetId; std::map bindParam; - int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam); + int sessionId = 1; + int64_t logicalSessionId = 888; + int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam, sessionId, logicalSessionId); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -924,7 +926,9 @@ HWTEST_F(DmAuthManagerTest, BindTarget_002, testing::ext::TestSize.Level1) std::string pkgName = "pkgName"; PeerTargetId targetId; std::map bindParam; - int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam); + int sessionId = 1; + int64_t logicalSessionId = 888; + int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam, sessionId, logicalSessionId); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -936,7 +940,9 @@ HWTEST_F(DmAuthManagerTest, BindTarget_004, testing::ext::TestSize.Level1) std::map bindParam; bindParam.insert(std::pair("AUTH_TYPE", "1")); bindParam.insert(std::pair("CONN_ADDR_TYPE", "3")); - int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam); + int sessionId = 1; + int64_t logicalSessionId = 888; + int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam, sessionId, logicalSessionId); ASSERT_EQ(ret, ERR_DM_AUTH_BUSINESS_BUSY); } @@ -948,7 +954,9 @@ HWTEST_F(DmAuthManagerTest, BindTarget_005, testing::ext::TestSize.Level1) std::map bindParam; bindParam.insert(std::pair("AUTH_TYPE", "2")); bindParam.insert(std::pair("CONN_ADDR_TYPE", "3")); - int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam); + int sessionId = 1; + int64_t logicalSessionId = 888; + int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam, sessionId, logicalSessionId); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -1735,7 +1743,9 @@ HWTEST_F(DmAuthManagerTest, BindTarget_006, testing::ext::TestSize.Level1) std::map bindParam; bindParam.insert(std::pair("AUTH_TYPE", "2")); bindParam.insert(std::pair("CONN_ADDR_TYPE", "3")); - int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam); + int sessionId = 1; + int64_t logicalSessionId = 888; + int32_t ret = authManager_->BindTarget(pkgName, targetId, bindParam, sessionId, logicalSessionId); ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_AUTH_TYPE); } } // namespace diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.cpp b/test/commonunittest/UTTest_dm_auth_manager_third.cpp index 2e644498e..559b079e2 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_third.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_third.cpp @@ -344,7 +344,7 @@ HWTEST_F(DmAuthManagerTest, DeleteAccessControlList004, testing::ext::TestSize.L std::string pkgName = "pkgName"; std::string localDeviceId = "localDeviceId"; std::string remoteDeviceId = "remoteDeviceId"; - int32_t bindLevel = DEVICE; + int32_t bindLevel = USER; std::string extra = ""; auto ret = DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId, bindLevel, extra); diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 52821ab12..e1e10cd16 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -686,7 +686,7 @@ HWTEST_F(DeviceProfileConnectorTest, HandleDmAuthForm_002, testing::ext::TestSiz { DistributedDeviceProfile::AccessControlProfile profiles; profiles.SetBindType(DM_POINT_TO_POINT); - profiles.SetBindLevel(DEVICE); + profiles.SetBindLevel(USER); DmDiscoveryInfo discoveryInfo; int32_t ret = DeviceProfileConnector::GetInstance().HandleDmAuthForm(profiles, discoveryInfo); EXPECT_EQ(ret, PEER_TO_PEER); @@ -724,7 +724,7 @@ HWTEST_F(DeviceProfileConnectorTest, HandleDmAuthForm_005, testing::ext::TestSiz { DistributedDeviceProfile::AccessControlProfile profiles; profiles.SetBindType(DM_ACROSS_ACCOUNT); - profiles.SetBindLevel(DEVICE); + profiles.SetBindLevel(USER); DmDiscoveryInfo discoveryInfo; int32_t ret = DeviceProfileConnector::GetInstance().HandleDmAuthForm(profiles, discoveryInfo); EXPECT_EQ(ret, ACROSS_ACCOUNT); @@ -989,7 +989,7 @@ HWTEST_F(DeviceProfileConnectorTest, ProcessBindType_003, testing::ext::TestSize { DistributedDeviceProfile::AccessControlProfile profiles; profiles.SetBindType(DM_POINT_TO_POINT); - profiles.SetBindLevel(DEVICE); + profiles.SetBindLevel(USER); std::string targetDeviceId = "targetDeviceId"; std::string localDeviceId = "localDeviceId"; uint32_t index = 0; @@ -1005,7 +1005,7 @@ HWTEST_F(DeviceProfileConnectorTest, ProcessBindType_004, testing::ext::TestSize { DistributedDeviceProfile::AccessControlProfile profiles; profiles.SetBindType(DM_ACROSS_ACCOUNT); - profiles.SetBindLevel(DEVICE); + profiles.SetBindLevel(USER); std::string targetDeviceId = "targetDeviceId"; std::string localDeviceId = "localDeviceId"; uint32_t index = 0; @@ -1120,11 +1120,11 @@ HWTEST_F(DeviceProfileConnectorTest, GetAuthForm_001, testing::ext::TestSize.Lev ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); EXPECT_EQ(ret, IDENTICAL_ACCOUNT_TYPE); profile.SetBindType(DM_POINT_TO_POINT); - profile.SetBindLevel(DEVICE); + profile.SetBindLevel(USER); ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); EXPECT_EQ(ret, DEVICE_PEER_TO_PEER_TYPE); profile.SetBindType(DM_ACROSS_ACCOUNT); - profile.SetBindLevel(DEVICE); + profile.SetBindLevel(USER); ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); EXPECT_EQ(ret, DEVICE_ACROSS_ACCOUNT_TYPE); profile.SetBindLevel(APP); @@ -1157,20 +1157,20 @@ HWTEST_F(DeviceProfileConnectorTest, GetBindLevel_001, testing::ext::TestSize.Le HWTEST_F(DeviceProfileConnectorTest, UpdateBindType_001, testing::ext::TestSize.Level1) { std::string udid = "deviceId"; - int32_t bindType = DEVICE; + int32_t bindType = USER; std::map deviceMap; deviceMap[udid] = APP; DeviceProfileConnector::GetInstance().UpdateBindType(udid, bindType, deviceMap); - EXPECT_EQ(deviceMap[udid], DEVICE); + EXPECT_EQ(deviceMap[udid], USER); } HWTEST_F(DeviceProfileConnectorTest, UpdateBindType_002, testing::ext::TestSize.Level1) { std::string udid = "deviceId"; - int32_t bindType = DEVICE; + int32_t bindType = USER; std::map deviceMap; DeviceProfileConnector::GetInstance().UpdateBindType(udid, bindType, deviceMap); - EXPECT_EQ(deviceMap[udid], DEVICE); + EXPECT_EQ(deviceMap[udid], USER); } HWTEST_F(DeviceProfileConnectorTest, HandleAccountLogoutEvent_001, testing::ext::TestSize.Level1) @@ -1192,8 +1192,9 @@ HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_001, testing::ext::Tes std::string remoteUdid = "remoteDeviceId"; std::string localUdid = "localDeviceId"; int32_t bindType = DM_INVALIED_BINDTYPE; - - bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + DmOfflineParam offlineParam; + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, + offlineParam); EXPECT_EQ(bindType, DM_INVALIED_BINDTYPE); } @@ -1204,15 +1205,15 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_001, testing::ext::Tes std::string remoteUdid = "remoteDeviceId"; std::string localUdid = "localDeviceId"; std::string pkgName = ""; - ProcessInfo res; + DmOfflineParam res; res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); - EXPECT_EQ(pkgName, res.pkgName); + EXPECT_EQ(0, res.processVec.size()); int32_t peerTokenId = 1; res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, peerTokenId); - EXPECT_EQ(pkgName, res.pkgName); + EXPECT_EQ(0, res.processVec.size()); } HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSize.Level1) @@ -1228,7 +1229,7 @@ HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSi ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); EXPECT_EQ(ret, true); profile.SetBindType(DM_POINT_TO_POINT); - profile.SetBindLevel(DEVICE); + profile.SetBindLevel(USER); ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); EXPECT_EQ(ret, true); profile.SetBindLevel(APP); @@ -1238,7 +1239,7 @@ HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSi ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); EXPECT_EQ(ret, true); profile.SetBindType(DM_ACROSS_ACCOUNT); - profile.SetBindLevel(DEVICE); + profile.SetBindLevel(USER); ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); EXPECT_EQ(ret, true); profile.SetBindLevel(APP); @@ -1254,7 +1255,7 @@ HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSi HWTEST_F(DeviceProfileConnectorTest, GetAccessControlProfileByUserId_001, testing::ext::TestSize.Level1) { - int32_t userId = DEVICE; + int32_t userId = USER; std::vector profiles; profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfileByUserId(userId); EXPECT_GE(profiles.size(), 0); @@ -1300,12 +1301,12 @@ HWTEST_F(DeviceProfileConnectorTest, DeleteDeviceBindLevel_001, testing::ext::Te std::string remoteUdid="localDeviceId"; GetAccessControlProfiles(profiles); DeviceProfileConnector::GetInstance().DeleteDeviceBindLevel(offlineParam, profiles, localUdid, remoteUdid); - EXPECT_EQ(offlineParam.bindType, DEVICE); + EXPECT_EQ(offlineParam.bindType, USER); localUdid = "localDeviceId"; remoteUdid="remoteDeviceId"; DeviceProfileConnector::GetInstance().DeleteDeviceBindLevel(offlineParam, profiles, localUdid, remoteUdid); - EXPECT_EQ(offlineParam.bindType, DEVICE); + EXPECT_EQ(offlineParam.bindType, USER); } HWTEST_F(DeviceProfileConnectorTest, DeleteServiceBindLevel_001, testing::ext::TestSize.Level1) @@ -1418,20 +1419,25 @@ HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_002, testing::ext::Tes std::string remoteUdid; std::string localUdid = "localDeviceId"; int32_t bindType = DM_INVALIED_BINDTYPE; - bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + DmOfflineParam offlineParam; + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, + offlineParam); EXPECT_EQ(bindType, DM_INVALIED_BINDTYPE); remoteUdid = "123456"; - bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, + offlineParam); EXPECT_EQ(bindType, DM_INVALIED_BINDTYPE); remoteUdid = "localDeviceId"; remoteUserId = 1234; - bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, + offlineParam); EXPECT_EQ(bindType, DM_IDENTICAL_ACCOUNT); remoteUserId = 456; - bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid, + offlineParam); EXPECT_EQ(bindType, 3); } @@ -1863,23 +1869,23 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_002, testing::ext::Tes std::string remoteUdid = "localDeviceId"; std::string localUdid = "remoteDeviceId"; std::string pkgName = ""; - ProcessInfo res; + DmOfflineParam res; res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); - EXPECT_EQ("bundleName", res.pkgName); + EXPECT_EQ(0, res.processVec.size()); int32_t peerTokenId = 1001; res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, peerTokenId); - EXPECT_EQ("bundleName", res.pkgName); + EXPECT_EQ(0, res.processVec.size()); tokenId = 1002; peerTokenId = tokenId; res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); - EXPECT_EQ("bundleName", res.pkgName); + EXPECT_EQ(0, res.processVec.size()); res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, peerTokenId); - EXPECT_EQ("bundleName", res.pkgName); + EXPECT_EQ(0, res.processVec.size()); } HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_003, testing::ext::TestSize.Level1) @@ -1890,10 +1896,10 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_003, testing::ext::Tes std::string localUdid = "localDeviceId"; std::string pkgName = ""; int32_t peerTokenId = 1001; - ProcessInfo res; + DmOfflineParam res; res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, peerTokenId); - EXPECT_EQ(pkgName, res.pkgName); + EXPECT_EQ(0, res.processVec.size()); } HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_004, testing::ext::TestSize.Level1) @@ -1904,10 +1910,10 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_004, testing::ext::Tes std::string localUdid = "localDeviceId"; std::string pkgName = ""; int32_t peerTokenId = 1001; - ProcessInfo res; + DmOfflineParam res; res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, peerTokenId); - EXPECT_EQ("bundleName", res.pkgName); + EXPECT_EQ(0, res.processVec.size()); } HWTEST_F(DeviceProfileConnectorTest, GetTokenIdByNameAndDeviceId_002, testing::ext::TestSize.Level1) @@ -2215,7 +2221,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetBindLevel_002, testing::ext::TestSize.Le udid = "deviceId"; EXPECT_CALL(*multipleUserConnectorMock_, GetFirstForegroundUserId()).WillOnce(Return(123456)); bindLevel = DeviceProfileConnector::GetInstance().GetBindLevel(pkgName, localUdid, udid, tokenId); - EXPECT_EQ(bindLevel, DEVICE); + EXPECT_EQ(bindLevel, USER); int32_t bindType = 256; std::string peerUdid = "123456"; diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp index 523d6d259..ac0a4ecd7 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp @@ -121,7 +121,7 @@ HWTEST_F(DeviceProfileConnectorSecondTest, GetAccessControlProfile_201, testing: HWTEST_F(DeviceProfileConnectorSecondTest, GetAccessControlProfileByUserId_201, testing::ext::TestSize.Level1) { - int32_t userId = DEVICE; + int32_t userId = USER; std::vector profiles; EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfileByUserId(userId); @@ -151,7 +151,7 @@ HWTEST_F(DeviceProfileConnectorSecondTest, CheckAuthForm_201, testing::ext::Test ret = DeviceProfileConnector::GetInstance().CheckAuthForm(form, profiles, discoveryInfo); EXPECT_EQ(ret, DmAuthForm::INVALID_TYPE); - profiles.SetBindLevel(DEVICE); + profiles.SetBindLevel(USER); ret = DeviceProfileConnector::GetInstance().CheckAuthForm(form, profiles, discoveryInfo); EXPECT_EQ(ret, DmAuthForm::ACROSS_ACCOUNT); } diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index a33d4b17b..9058c5861 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -67,18 +67,12 @@ public: (void)sessionKey; (void)sessionKeyLen; } - int32_t GetPinCode(int32_t &code) override + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override { - if (pinCode == 0) { - code = 0; - return DM_OK; - } - code = ERR_DM_AUTH_NOT_START; - return ERR_DM_AUTH_NOT_START; - } - void GetRemoteDeviceId(std::string &deviceId) override - { - (void)deviceId; + (void)requestId; + (void)operationCode; + (void)reqParams; + return nullptr; } private: int32_t pinCode = 0; @@ -162,20 +156,6 @@ HWTEST_F(HiChainAuthConnectorTest, onRequest_003, testing::ext::TestSize.Level1) EXPECT_NE(hiChain_->dmDeviceAuthCallback_, nullptr); } -HWTEST_F(HiChainAuthConnectorTest, onRequest_004, testing::ext::TestSize.Level1) -{ - int64_t requestId = 0; - int operationCode = 0; - char *reqParams = nullptr; - std::shared_ptr hiChainAuthConnector = std::make_shared(); - std::shared_ptr mockCallback = std::make_shared(); - hiChainAuthConnector->dmDeviceAuthCallback_ = mockCallback; - EXPECT_CALL(*mockCallback, GetPinCode(testing::_)) - .Times(1) - .WillOnce(testing::Return(ERR_DM_FAILED)); - EXPECT_NE(hiChainAuthConnector->onRequest(requestId, operationCode, reqParams), nullptr); -} - HWTEST_F(HiChainAuthConnectorTest, onFinish_001, testing::ext::TestSize.Level1) { int64_t requestId = 0; diff --git a/test/commonunittest/UTTest_hichain_auth_connector.h b/test/commonunittest/UTTest_hichain_auth_connector.h index 3c708b598..fdff7c0cb 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.h +++ b/test/commonunittest/UTTest_hichain_auth_connector.h @@ -44,8 +44,7 @@ public: MOCK_METHOD(void, AuthDeviceError, (int64_t requestId, int32_t errorCode), (override)); MOCK_METHOD(void, AuthDeviceSessionKey, (int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen), (override)); - MOCK_METHOD(void, GetRemoteDeviceId, (std::string &deviceId), (override)); - MOCK_METHOD(int32_t, GetPinCode, (int32_t &code), (override)); + MOCK_METHOD(char *, AuthDeviceRequest, (int64_t requestId, int operationCode, const char *reqParams), (override)); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp b/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp index 2d0979540..2fe1110fd 100644 --- a/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp +++ b/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp @@ -57,11 +57,9 @@ void OnBytesReceivedFuzzTest(const uint8_t* data, size_t size) if ((data == nullptr) || (size < sizeof(int))) { return; } - int sessionId = *(reinterpret_cast(data)); std::shared_ptr softbusSession = std::make_shared(); softbusSession->RegisterSessionCallback(std::make_shared()); - softbusSession->OnBytesReceived(sessionId, data, size); } } } diff --git a/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp b/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp index a079a5c9e..9df6f8cdc 100644 --- a/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp +++ b/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp @@ -70,7 +70,6 @@ void SoftBusSessionFuzzTest(const uint8_t* data, size_t size) softbusSession->OnSessionOpened(result, result); softbusSession->OpenAuthSession(str); softbusSession->CloseAuthSession(sessionId); - softbusSession->OnBytesReceived(result, str.c_str(), str.size()); softbusSession->GetPeerDeviceId(sessionId, str); softbusSession->SendData(sessionId, str); softbusSession->SendHeartbeatData(sessionId, str); diff --git a/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp b/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp index fe688c42f..3d76c29ca 100644 --- a/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp +++ b/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp @@ -58,21 +58,8 @@ void SoftBusSessionFuzzTest(const uint8_t* data, size_t size) return; } - int32_t socket = *(reinterpret_cast(data)); - QoSEvent eventId = static_cast(1); - uint32_t qosCount = 3; - QosTV qos[] = { - { .qos = QOS_TYPE_MIN_BW, .value = 64 * 1024 }, - { .qos = QOS_TYPE_MAX_LATENCY, .value = 19000}, - { .qos = QOS_TYPE_MIN_LATENCY, .value = 500 }, - }; - ShutdownReason reason = ShutdownReason::SHUTDOWN_REASON_UNKNOWN; - std::shared_ptr softbusSession = std::make_shared(); softbusSession->RegisterSessionCallback(std::make_shared()); - softbusSession->iSocketListener_.OnBytes(socket, data, size); - softbusSession->iSocketListener_.OnShutdown(socket, reason); - softbusSession->iSocketListener_.OnQos(socket, eventId, qos, qosCount); } } } diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index c510b8492..deb4a4b08 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -220,7 +220,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_001, testing::ext::TestSize.Level1 std::string deviceId; std::string connectAddr; std::shared_ptr softbusConnector = std::make_shared(); - ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + std::shared_ptr ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); EXPECT_EQ(ret, nullptr); } @@ -237,7 +237,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_002, testing::ext::TestSize.Level1 DeviceInfo deviceInfo; deviceInfo.addrNum = -1; std::shared_ptr softbusConnector = std::make_shared(); - ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + std::shared_ptr ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); EXPECT_EQ(ret, nullptr); } @@ -259,7 +259,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_003, testing::ext::TestSize.Level1 deviceInfo->addr[0].info.ip.port = 0; SoftbusConnector::discoveryDeviceInfoMap_[deviceId] = deviceInfo; std::shared_ptr softbusConnector = std::make_shared(); - ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + std::shared_ptr ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); EXPECT_NE(ret, nullptr); SoftbusConnector::discoveryDeviceInfoMap_.clear(); } @@ -282,7 +282,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_004, testing::ext::TestSize.Level1 deviceInfo->addr[0].info.ip.port = 0; SoftbusConnector::discoveryDeviceInfoMap_[deviceId] = deviceInfo; std::shared_ptr softbusConnector = std::make_shared(); - ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + std::shared_ptr ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); EXPECT_NE(ret, nullptr); SoftbusConnector::discoveryDeviceInfoMap_.clear(); } @@ -304,7 +304,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_005, testing::ext::TestSize.Level1 (void)strncpy_s(deviceInfo->addr[0].info.br.brMac, IP_STR_MAX_LEN, brMac, strlen(brMac)); SoftbusConnector::discoveryDeviceInfoMap_[deviceId] = deviceInfo; std::shared_ptr softbusConnector = std::make_shared(); - ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + std::shared_ptr ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); EXPECT_NE(ret, nullptr); SoftbusConnector::discoveryDeviceInfoMap_.clear(); } @@ -326,7 +326,7 @@ HWTEST_F(SoftbusConnectorTest, GetConnectAddr_006, testing::ext::TestSize.Level1 (void)strncpy_s(deviceInfo->addr[0].info.ble.bleMac, IP_STR_MAX_LEN, bleMac, strlen(bleMac)); SoftbusConnector::discoveryDeviceInfoMap_[deviceId] = deviceInfo; std::shared_ptr softbusConnector = std::make_shared(); - ConnectionAddr *ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); + std::shared_ptr ret = softbusConnector->GetConnectAddr(deviceId, connectAddr); EXPECT_NE(ret, nullptr); SoftbusConnector::discoveryDeviceInfoMap_.clear(); } diff --git a/test/softbusunittest/UTTest_softbus_session.cpp b/test/softbusunittest/UTTest_softbus_session.cpp index e5618bb35..71275de55 100644 --- a/test/softbusunittest/UTTest_softbus_session.cpp +++ b/test/softbusunittest/UTTest_softbus_session.cpp @@ -241,12 +241,7 @@ HWTEST_F(SoftbusSessionTest, OnSessionOpened_001, testing::ext::TestSize.Level1) softbusSession->RegisterSessionCallback(discoveryMgr); int sessionId = 1; int result = 0; - void *data = nullptr; - unsigned int dataLen = 1; - softbusSession->OnBytesReceived(sessionId, data, dataLen); - softbusSession->OnBytesReceived(sessionId, data, -1); - sessionId = -1; - softbusSession->OnBytesReceived(sessionId, data, dataLen); + int ret = softbusSession->OnSessionOpened(sessionId, result); softbusSession->OnSessionClosed(sessionId); EXPECT_EQ(ret, DM_OK); diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 01d95d171..317d859b5 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -91,6 +91,7 @@ group("unittest") { ":UTTest_softbus_listener_two", ":UTTest_softbus_publish", ":UTTest_softbus_session", + ":UTTest_auth_pin_auth_state", ] } @@ -1186,7 +1187,6 @@ ohos_unittest("UTTest_device_manager_service_impl") { module_out_path = module_out_path sources = [ - "${devicemanager_path}/commondependency/src/multiple_user_connector.cpp", "${servicesimpl_path}/src/device_manager_service_impl.cpp", "UTTest_device_manager_service_impl.cpp", "mock/deviceprofile_connector_mock.cpp", @@ -1948,6 +1948,37 @@ ohos_unittest("UTTest_json_object") { ## UnitTest UTTest_json_object }}} +## UnitTest UTTest_auth_pin_auth_state {{{ + +ohos_unittest("UTTest_auth_pin_auth_state") { + module_out_path = module_out_path + + include_dirs = [ + + ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_auth_pin_auth_state.cpp", + "${devicemanager_path}/test/unittest/mock/hichain_auth_connector_mock.cpp", + "${devicemanager_path}/test/unittest/mock/dm_auth_state_machine_mock.cpp" + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "dsoftbus:softbus_client", + "googletest:gmock", + "googletest:gmock_main", + "hilog:libhilog", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "device_auth:deviceauth_sdk", + "ffrt:libffrt", + ] +} + +## UnitTest UTTest_auth_pin_auth_state }}} + ## Build device_manager_test_common.a {{{ config("device_manager_test_common_public_config") { include_dirs = [ diff --git a/test/unittest/UTTest_auth_credential_state.cpp b/test/unittest/UTTest_auth_credential_state.cpp new file mode 100644 index 000000000..e14e1f007 --- /dev/null +++ b/test/unittest/UTTest_auth_credential_state.cpp @@ -0,0 +1,764 @@ +/* + * Copyright (c) 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 "dm_auth_state.h" +#include "UTTest_auth_credential_state.h" +#include "dm_auth_message_processor_mock.h" +#include "device_manager_service_listener.h" + +using namespace testing; + +namespace OHOS { +namespace DistributedHardware { + +constexpr const char *TEST_NONE_EMPTY_STRING = "test"; + +void AuthCredentialStateTest::SetUpTestCase() +{ + LOGI("AuthCredentialStateTest::SetUpTestCase start."); + DmHiChainAuthConnector::dmHiChainAuthConnector = dmHiChainAuthConnectorMock; + DmSoftbusSession::dmSoftbusSession = dmSoftbusSessionMock; + DmAuthStateMachineMock::dmAuthStateMachineMock = dmAuthStateMachineMock; + DmAuthMessageProcessorMock::dmAuthMessageProcessorMock = std::make_shared(); +} + +void AuthCredentialStateTest::TearDownTestCase() +{ + LOGI("AuthCredentialStateTest::TearDownTestCase start."); + DmHiChainAuthConnector::dmHiChainAuthConnector = nullptr; + dmHiChainAuthConnectorMock = nullptr; + DmSoftbusSession::dmSoftbusSession = nullptr; + dmSoftbusSessionMock = nullptr; + DmAuthStateMachineMock::dmAuthStateMachineMock = nullptr; + dmAuthStateMachineMock = nullptr; + DmAuthMessageProcessorMock::dmAuthMessageProcessorMock = nullptr; +} + +void AuthCredentialStateTest::SetUp() +{ + LOGI("AuthCredentialStateTest::SetUp start."); + softbusConnector = std::make_shared(); + listener = std::make_shared(); + hiChainAuthConnector = std::make_shared(); + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + + Mock::VerifyAndClearExpectations(&*DmHiChainAuthConnector::dmHiChainAuthConnector); + Mock::VerifyAndClearExpectations(&*DmSoftbusSession::dmSoftbusSession); + Mock::VerifyAndClearExpectations(&*DmAuthStateMachineMock::dmAuthStateMachineMock); + Mock::VerifyAndClearExpectations(&*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock); +} + +void AuthCredentialStateTest::TearDown() +{ + LOGI("AuthCredentialStateTest::TearDown start."); + softbusConnector = nullptr; + listener = nullptr; + hiChainAuthConnector = nullptr; + authManager = nullptr; + context = nullptr; +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)).WillRepeatedly(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)).WillRepeatedly(Return(DM_OK)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(ERR_DM_FAILED)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_008, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_009, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_FINISH)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_008, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_008, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_008, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_009, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return("")); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_0010, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +} +} \ No newline at end of file diff --git a/test/unittest/UTTest_auth_credential_state.h b/test/unittest/UTTest_auth_credential_state.h new file mode 100644 index 000000000..ba2893051 --- /dev/null +++ b/test/unittest/UTTest_auth_credential_state.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 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. + */ + +#ifndef UTTEST_AUTH_CREDENTIAL_STATE_H +#define UTTEST_AUTH_CREDENTIAL_STATE_H + +#include +#include "hichain_auth_connector_mock.h" +#include "softbus_session_mock.h" +#include "dm_auth_state_machine_mock.h" +#include "auth_manager.h" + +namespace OHOS { +namespace DistributedHardware { + +class AuthCredentialStateTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +private: + static inline std::shared_ptr dmHiChainAuthConnectorMock = + std::make_shared(); + static inline std::shared_ptr dmSoftbusSessionMock = + std::make_shared(); + static inline std::shared_ptr dmAuthStateMachineMock = + std::make_shared(); + std::shared_ptr softbusConnector; + std::shared_ptr listener; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authManager; + std::shared_ptr context; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/UTTest_auth_negotiate_state.cpp b/test/unittest/UTTest_auth_negotiate_state.cpp new file mode 100644 index 000000000..c9b83d863 --- /dev/null +++ b/test/unittest/UTTest_auth_negotiate_state.cpp @@ -0,0 +1,141 @@ +/* + * Copyright (c) 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 "device_manager_service_listener.h" +#include "dm_auth_state.h" +#include "UTTest_auth_negotiate_state.h" + +using namespace testing; + +namespace OHOS { +namespace DistributedHardware { + +constexpr const char* TEST_STRING = "test_string"; +constexpr int32_t TEST_NEGATIVE = -1; +constexpr int32_t TEST_POSITIVE = 1; + +void AuthNegotiateStateTest::SetUpTestCase() +{ + LOGI("AuthNegotiateStateTest::SetUpTestCase start."); + + DmSoftbusConnector::dmSoftbusConnector = softbusConnectorMock; + DmSoftbusSession::dmSoftbusSession = softbusSessionMock; +} + +void AuthNegotiateStateTest::TearDownTestCase() +{ + LOGI("AuthNegotiateStateTest::TearDownTestCase done."); + softbusConnectorMock = nullptr; + softbusSessionMock = nullptr; + DmSoftbusConnector::dmSoftbusConnector = nullptr; + DmSoftbusSession::dmSoftbusSession = nullptr; +} + +void AuthNegotiateStateTest::SetUp() +{ + LOGI("AuthNegotiateStateTest::SetUp start."); + softbusConnector = std::make_shared(); + listener = std::make_shared(); + hiChainAuthConnector = std::make_shared(); + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + softbusSession = std::make_shared(); + + Mock::VerifyAndClearExpectations(&*softbusConnectorMock); + Mock::VerifyAndClearExpectations(&*softbusSessionMock); +} + +void AuthNegotiateStateTest::TearDown() +{ + LOGI("AuthNegotiateStateTest::TearDown done."); + softbusConnector = nullptr; + listener = nullptr; + hiChainAuthConnector = nullptr; + authManager = nullptr; + context = nullptr; + softbusSession = nullptr; +} + +HWTEST_F(AuthNegotiateStateTest, AuthSrcStartState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_START_STATE); +} + +HWTEST_F(AuthNegotiateStateTest, AuthSrcStartState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + context->connSessionType = CONN_SESSION_TYPE_HML; + + EXPECT_CALL(*softbusConnectorMock, GetSoftbusSession) + .WillOnce(Return(softbusSession)); + + EXPECT_CALL(*softbusSessionMock, OpenAuthSessionWithPara) + .WillOnce(Return(TEST_POSITIVE)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthNegotiateStateTest, AuthSrcStartState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + context->connSessionType = TEST_STRING; + + EXPECT_CALL(*softbusConnectorMock, GetSoftbusSession()) + .WillOnce(Return(softbusSession)); + + EXPECT_CALL(*softbusSessionMock, OpenAuthSession(_)) + .WillOnce(Return(TEST_POSITIVE)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthNegotiateStateTest, AuthSrcStartState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + context->connSessionType = CONN_SESSION_TYPE_HML; + + EXPECT_CALL(*softbusConnectorMock, GetSoftbusSession) + .WillOnce(Return(softbusSession)); + + EXPECT_CALL(*softbusSessionMock, OpenAuthSessionWithPara) + .WillOnce(Return(TEST_NEGATIVE)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthNegotiateStateTest, AuthSrcNegotiateStateMachine_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE); +} + +HWTEST_F(AuthNegotiateStateTest, AuthSrcNegotiateStateMachine_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthNegotiateStateTest, AuthSinkNegotiateStateMachine_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE); +} +} +} \ No newline at end of file diff --git a/test/unittest/UTTest_auth_negotiate_state.h b/test/unittest/UTTest_auth_negotiate_state.h new file mode 100644 index 000000000..d385723bc --- /dev/null +++ b/test/unittest/UTTest_auth_negotiate_state.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 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. + */ + +#ifndef UTTEST_AUTH_NEGOTIATE_STATE_H +#define UTTEST_AUTH_NEGOTIATE_STATE_H + +#include "gtest/gtest.h" +#include "auth_manager.h" +#include "softbus_connector_mock.h" +#include "softbus_session_mock.h" + +namespace OHOS { +namespace DistributedHardware { + +class AuthNegotiateStateTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +private: + static inline std::shared_ptr softbusConnectorMock = + std::make_shared(); + static inline std::shared_ptr softbusSessionMock = + std::make_shared(); + std::shared_ptr softbusConnector; + std::shared_ptr listener; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authManager; + std::shared_ptr context; + std::shared_ptr softbusSession; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/UTTest_auth_pin_auth_state.cpp b/test/unittest/UTTest_auth_pin_auth_state.cpp new file mode 100644 index 000000000..55ed28fc6 --- /dev/null +++ b/test/unittest/UTTest_auth_pin_auth_state.cpp @@ -0,0 +1,412 @@ +/* + * Copyright (c) 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 "dm_auth_state_machine_mock.h" +#include "UTTest_auth_pin_auth_state.h" + +using namespace testing; + +namespace OHOS { +namespace DistributedHardware { + +void AuthPinAuthStateTest::SetUpTestCase() +{ + LOGI("AuthPinAuthStateTest::SetUpTestCase start."); + DmHiChainAuthConnector::dmHiChainAuthConnector = hiChainAuthConnectorMock; + DmAuthStateMachineMock::dmAuthStateMachineMock = std::make_shared(); +} + +void AuthPinAuthStateTest::TearDownTestCase() +{ + LOGI("AuthPinAuthStateTest::TearDownTestCase start."); + DmHiChainAuthConnector::dmHiChainAuthConnector = nullptr; + DmAuthStateMachineMock::dmAuthStateMachineMock = nullptr; + hiChainAuthConnectorMock = nullptr; +} + +void AuthPinAuthStateTest::SetUp() +{ + LOGI("AuthPinAuthStateTest::SetUp start."); + softbusConnector = std::make_shared(); + listener = std::make_shared(); + hiChainAuthConnector = std::make_shared(); + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + + Mock::VerifyAndClearExpectations(&*hiChainAuthConnectorMock); + Mock::VerifyAndClearExpectations(&*DmAuthStateMachineMock::dmAuthStateMachineMock); +} + +void AuthPinAuthStateTest::TearDown() +{ + LOGI("AuthPinAuthStateTest::TearDown start."); + softbusConnector = nullptr; + listener = nullptr; + hiChainAuthConnector = nullptr; + authManager = nullptr; + context = nullptr; +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, AuthCredentialPinCode(_, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, AuthCredentialPinCode(_, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, AuthCredentialPinCode(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, AuthCredentialPinCode(_, _, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_REQUEST)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_REQUEST)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_REQUEST)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_REQUEST)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthDoneState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE); +} + +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthDoneState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_EQ(authState->Action(context), DM_OK); +} +} +} \ No newline at end of file diff --git a/test/unittest/UTTest_auth_pin_auth_state.h b/test/unittest/UTTest_auth_pin_auth_state.h new file mode 100644 index 000000000..0cd480ebd --- /dev/null +++ b/test/unittest/UTTest_auth_pin_auth_state.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 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. + */ + +#ifndef UTTEST_AUTH_PIN_AUTH_STATE_H +#define UTTEST_AUTH_PIN_AUTH_STATE_H + +#include +#include "device_manager_service_listener.h" +#include "hichain_auth_connector_mock.h" +#include "auth_manager.h" + +namespace OHOS { +namespace DistributedHardware { + +class AuthPinAuthStateTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +private: + static inline std::shared_ptr hiChainAuthConnectorMock = + std::make_shared(); + std::shared_ptr softbusConnector; + std::shared_ptr listener; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authManager; + std::shared_ptr context; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 08e5dd4e5..da0f2fe3f 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2211,7 +2211,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_003, testing::ext::TestSize.Level std::vector peerUdids; int32_t userId = 1; uint64_t tokenId = 87; - DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, DEVICE); + DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, USER); DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, APP); DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, 2); DeviceManagerService::GetInstance().SendDeviceUnBindBroadCast(peerUdids, userId); diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 22b4d9c4b..eed43a768 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -69,7 +69,7 @@ void AddAccessControlProfileFirst(std::vector& accessContr int32_t userId = 123456; int32_t bindType = 4; int32_t deviceIdType = 1; - uint32_t bindLevel = DEVICE; + uint32_t bindLevel = USER; uint32_t status = 0; uint32_t authenticationType = 2; uint32_t accesserId = 1; @@ -120,7 +120,7 @@ void AddAccessControlProfileSecond(std::vector& accessCont int32_t userId = 123456; int32_t bindType = 1; int32_t deviceIdType = 1; - uint32_t bindLevel = DEVICE; + uint32_t bindLevel = USER; uint32_t status = 0; uint32_t authenticationType = 2; uint32_t accesserId = 1; @@ -171,7 +171,7 @@ void AddAccessControlProfileThird(std::vector& accessContr int32_t userId = 123456; int32_t bindType = 4; int32_t deviceIdType = 1; - uint32_t bindLevel = DEVICE; + uint32_t bindLevel = USER; uint32_t status = 0; uint32_t authenticationType = 2; uint32_t accesserId = 1; @@ -1778,7 +1778,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_003, testing::ext::TestSize std::map userIdAndBindLevel; userIdAndBindLevel[1] = INVALIED_TYPE; - userIdAndBindLevel[2] = DEVICE; + userIdAndBindLevel[2] = USER; userIdAndBindLevel[3] = SERVICE; userIdAndBindLevel[4] = APP; std::vector profiles; @@ -1895,21 +1895,23 @@ HWTEST_F(DeviceManagerServiceImplTest, SaveOnlineDeviceInfo_001, testing::ext::T int32_t remoteUserId = 1; std::string remoteUdid = "remoteDeviceId"; int32_t tokenId = 0; - ProcessInfo processInfo; - EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return(processInfo)); + DmOfflineParam dmOfflineParam; + EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return(dmOfflineParam)); deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId); + ProcessInfo processInfo; processInfo.pkgName = "pkgName"; + dmOfflineParam.processVec.push_back(processInfo); if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } - EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return(processInfo)); + EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return(dmOfflineParam)); deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId); - EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _)).WillOnce(Return(DM_INVALIED_BINDTYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _, _)).WillOnce(Return(DM_INVALIED_BINDTYPE)); deviceManagerServiceImpl_->HandleDevUnBindEvent(remoteUserId, remoteUdid); - EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); if (deviceManagerServiceImpl_->authMgr_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } @@ -1975,14 +1977,16 @@ HWTEST_F(DeviceManagerServiceImplTest, GetTokenIdByNameAndDeviceId_001, testing: int32_t tokenId = 0; int32_t peerTokenId = 1; ProcessInfo processInfo; - EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _, _)).WillOnce(Return(processInfo)); + DmOfflineParam dmOfflineParam; + EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _, _)).WillOnce(Return(dmOfflineParam)); deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, peerTokenId); processInfo.pkgName = "pkgName"; + dmOfflineParam.processVec.push_back(processInfo); if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } - EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _, _)).WillOnce(Return(processInfo)); + EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _, _)).WillOnce(Return(dmOfflineParam)); deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, peerTokenId); int32_t bindType = 1; diff --git a/test/unittest/mock/deviceprofile_connector_mock.cpp b/test/unittest/mock/deviceprofile_connector_mock.cpp index fb16ca57d..bc54f698b 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.cpp +++ b/test/unittest/mock/deviceprofile_connector_mock.cpp @@ -26,10 +26,10 @@ std::vector DeviceProfileConnect } int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, - const std::string &localUdid) + const std::string &localUdid, DmOfflineParam &offlineParam) { return DmDeviceProfileConnector::dmDeviceProfileConnector->HandleDevUnBindEvent(remoteUserId, remoteUdid, - localUdid); + localUdid, offlineParam); } int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, @@ -57,7 +57,7 @@ bool DeviceProfileConnector::DeleteAclForAccountLogOut(const std::string &localU peerUdid, peerUserId); } -OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, +DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) { return DmDeviceProfileConnector::dmDeviceProfileConnector->HandleAppUnBindEvent(remoteUserId, remoteUdid, @@ -100,7 +100,7 @@ void DeviceProfileConnector::DeleteAclForRemoteUserRemoved(std::string peerUdid, userIds); } -OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, +DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid, int32_t peerTokenId) { return DmDeviceProfileConnector::dmDeviceProfileConnector->HandleAppUnBindEvent(remoteUserId, remoteUdid, diff --git a/test/unittest/mock/deviceprofile_connector_mock.h b/test/unittest/mock/deviceprofile_connector_mock.h index 2dee03bdf..cf464170e 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.h +++ b/test/unittest/mock/deviceprofile_connector_mock.h @@ -29,7 +29,7 @@ public: public: virtual std::vector GetAllAccessControlProfile() = 0; virtual int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, - const std::string &localUdid) = 0; + const std::string &localUdid, DmOfflineParam &offlineParam) = 0; virtual int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid) = 0; virtual uint32_t CheckBindType(std::string trustDeviceId, std::string requestDeviceId) = 0; @@ -37,7 +37,7 @@ public: const std::string &peerUdid) = 0; virtual bool DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, int32_t peerUserId) = 0; - virtual OHOS::DistributedHardware::ProcessInfo HandleAppUnBindEvent(int32_t remoteUserId, + virtual DmOfflineParam HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) = 0; virtual std::multimap GetDevIdAndUserIdByActHash(const std::string &localUdid, const std::string &peerUdid, int32_t peerUserId, const std::string &peerAccountHash) = 0; @@ -49,7 +49,7 @@ public: const std::string &remoteDeviceId, int32_t bindLevel, const std::string &extra) = 0; virtual void DeleteAclForRemoteUserRemoved(std::string peerUdid, int32_t peerUserId, std::vector &userIds) = 0; - virtual OHOS::DistributedHardware::ProcessInfo HandleAppUnBindEvent(int32_t remoteUserId, + virtual DmOfflineParam HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid, int32_t peerTokenId) = 0; virtual std::unordered_map GetAppTrustDeviceList(const std::string &pkgName, const std::string &deviceId) = 0; @@ -71,13 +71,13 @@ public: class DeviceProfileConnectorMock : public DmDeviceProfileConnector { public: MOCK_METHOD(std::vector, GetAllAccessControlProfile, ()); - MOCK_METHOD(int32_t, HandleDevUnBindEvent, (int32_t, const std::string &, const std::string &)); + MOCK_METHOD(int32_t, HandleDevUnBindEvent, (int32_t, const std::string &, const std::string &, DmOfflineParam &)); MOCK_METHOD(int32_t, HandleAccountLogoutEvent, (int32_t, const std::string &, const std::string &, const std::string &)); MOCK_METHOD(uint32_t, CheckBindType, (std::string, std::string)); MOCK_METHOD((std::map), GetUserIdAndBindLevel, (const std::string &, const std::string &)); MOCK_METHOD(bool, DeleteAclForAccountLogOut, (const std::string &, int32_t, const std::string &, int32_t)); - MOCK_METHOD((OHOS::DistributedHardware::ProcessInfo), HandleAppUnBindEvent, (int32_t, const std::string &, + MOCK_METHOD((DmOfflineParam), HandleAppUnBindEvent, (int32_t, const std::string &, int32_t, const std::string &)); MOCK_METHOD((std::multimap), GetDevIdAndUserIdByActHash, (const std::string &, const std::string &, int32_t, const std::string &)); @@ -87,7 +87,7 @@ public: MOCK_METHOD(DmOfflineParam, DeleteAccessControlList, (const std::string &, const std::string &, const std::string &, int32_t, const std::string &)); MOCK_METHOD(void, DeleteAclForRemoteUserRemoved, (std::string, int32_t, std::vector &)); - MOCK_METHOD((OHOS::DistributedHardware::ProcessInfo), HandleAppUnBindEvent, (int32_t, const std::string &, + MOCK_METHOD((DmOfflineParam), HandleAppUnBindEvent, (int32_t, const std::string &, int32_t, const std::string &, int32_t)); MOCK_METHOD((std::unordered_map), GetAppTrustDeviceList, (const std::string &, const std::string &)); diff --git a/test/unittest/mock/dm_auth_message_processor_mock.cpp b/test/unittest/mock/dm_auth_message_processor_mock.cpp new file mode 100644 index 000000000..e113adcad --- /dev/null +++ b/test/unittest/mock/dm_auth_message_processor_mock.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * 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 "dm_auth_message_processor_mock.h" + +namespace OHOS { +namespace DistributedHardware { + +int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t &skId) +{ + return DmAuthMessageProcessorMock::dmAuthMessageProcessorMock->SaveSessionKeyToDP(skId); +} + +} +} \ No newline at end of file diff --git a/test/unittest/mock/dm_auth_message_processor_mock.h b/test/unittest/mock/dm_auth_message_processor_mock.h new file mode 100644 index 000000000..5d9d35088 --- /dev/null +++ b/test/unittest/mock/dm_auth_message_processor_mock.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * 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 DM_AUTH_MESSAGE_PROCESSOR_MOCK_H +#define DM_AUTH_MESSAGE_PROCESSOR_MOCK_H + +#include +#include "dm_auth_message_processor.h" + +namespace OHOS { +namespace DistributedHardware { + +class DmAuthMessageProcessorMock { +public: + MOCK_METHOD(int32_t, SaveSessionKeyToDP, (int32_t &)); + MOCK_METHOD(std::string, CreateMessage, (DmMessageType, std::shared_ptr)); + static inline std::shared_ptr dmAuthMessageProcessorMock = nullptr; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/mock/dm_auth_state_machine_mock.cpp b/test/unittest/mock/dm_auth_state_machine_mock.cpp new file mode 100644 index 000000000..49da4bfb2 --- /dev/null +++ b/test/unittest/mock/dm_auth_state_machine_mock.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2023 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 "dm_auth_state_machine_mock.h" + +namespace OHOS { +namespace DistributedHardware { + +DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) +{ + return DmAuthStateMachineMock::dmAuthStateMachineMock->WaitExpectEvent(eventType); +} + +} +} \ No newline at end of file diff --git a/test/unittest/mock/dm_auth_state_machine_mock.h b/test/unittest/mock/dm_auth_state_machine_mock.h new file mode 100644 index 000000000..9489d08fd --- /dev/null +++ b/test/unittest/mock/dm_auth_state_machine_mock.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * 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 DM_AUTH_STATE_MACHINE_MOCK_H +#define DM_AUTH_STATE_MACHINE_MOCK_H + +#include +#include "dm_auth_state_machine.h" + +namespace OHOS { +namespace DistributedHardware { + +class DmAuthStateMachineMock { +public: + MOCK_METHOD(DmEventType, WaitExpectEvent, (DmEventType)); + static inline std::shared_ptr dmAuthStateMachineMock = nullptr; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/mock/hichain_auth_connector_mock.cpp b/test/unittest/mock/hichain_auth_connector_mock.cpp index e6c8451c8..dd7f98ffb 100644 --- a/test/unittest/mock/hichain_auth_connector_mock.cpp +++ b/test/unittest/mock/hichain_auth_connector_mock.cpp @@ -33,5 +33,43 @@ int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string { return DmHiChainAuthConnector::dmHiChainAuthConnector->ImportCredential(osAccountId, deviceId, publicKey); } + +int32_t HiChainAuthConnector::ProcessCredData(int64_t authReqId, const std::string &data) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->ProcessCredData(authReqId, data); +} + +int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::string &authParams, std::string &creId) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->AddCredential(osAccountId, authParams, creId); +} + +int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::string &credId, std::string &publicKey) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->ExportCredential(osAccountId, credId, publicKey); +} + +int32_t HiChainAuthConnector::AgreeCredential(int32_t osAccountId, const std::string selfCredId, + const std::string &authParams, std::string &credId) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->AgreeCredential(osAccountId, selfCredId, authParams, credId); +} + +int32_t HiChainAuthConnector::DeleteCredential(int32_t osAccountId, const std::string &creId) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->DeleteCredential(osAccountId, creId); +} + +int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, + const std::string &pinCode) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->AuthCredential(osAccountId, authReqId, credId, pinCode); +} + +int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->AuthCredentialPinCode(osAccountId, authReqId, pinCode); +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/hichain_auth_connector_mock.h b/test/unittest/mock/hichain_auth_connector_mock.h index 174867f64..d0de67f9e 100644 --- a/test/unittest/mock/hichain_auth_connector_mock.h +++ b/test/unittest/mock/hichain_auth_connector_mock.h @@ -30,6 +30,16 @@ public: virtual int32_t AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId) = 0; virtual int32_t ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey) = 0; + + virtual int32_t ProcessCredData(int64_t authReqId, const std::string &data) = 0; + virtual int32_t AddCredential(int32_t osAccountId, const std::string &authParams, std::string &creId) = 0; + virtual int32_t ExportCredential(int32_t osAccountId, const std::string &credId, std::string &publicKey) = 0; + virtual int32_t AgreeCredential(int32_t osAccountId, const std::string selfCredId, const std::string &authParams, + std::string &credId) = 0; + virtual int32_t DeleteCredential(int32_t osAccountId, const std::string &creId) = 0; + virtual int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, + const std::string &pinCode) = 0; + virtual int32_t AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode) = 0; public: static inline std::shared_ptr dmHiChainAuthConnector = nullptr; }; @@ -39,6 +49,14 @@ public: MOCK_METHOD(bool, QueryCredential, (std::string &, int32_t)); MOCK_METHOD(int32_t, AuthDevice, (int32_t, int32_t, std::string, int64_t)); MOCK_METHOD(int32_t, ImportCredential, (int32_t, std::string, std::string)); + + MOCK_METHOD(int32_t, ProcessCredData, (int64_t, const std::string &)); + MOCK_METHOD(int32_t, AddCredential, (int32_t, const std::string &, std::string &)); + MOCK_METHOD(int32_t, ExportCredential, (int32_t, const std::string &, std::string &)); + MOCK_METHOD(int32_t, AgreeCredential, (int32_t, const std::string, const std::string &, std::string &)); + MOCK_METHOD(int32_t, DeleteCredential, (int32_t, const std::string &)); + MOCK_METHOD(int32_t, AuthCredential, (int32_t, int64_t, const std::string &, const std::string &)); + MOCK_METHOD(int32_t, AuthCredentialPinCode, (int32_t, int64_t, int32_t)); }; } } diff --git a/test/unittest/mock/os_account_manager_mock.cpp b/test/unittest/mock/os_account_manager_mock.cpp index 50f194432..7a237c25e 100644 --- a/test/unittest/mock/os_account_manager_mock.cpp +++ b/test/unittest/mock/os_account_manager_mock.cpp @@ -41,5 +41,10 @@ ErrCode OsAccountManager::GetForegroundOsAccountLocalId(int32_t &localId) { return IOsAccountManager::GetOrCreateOsAccountManager()->GetForegroundOsAccountLocalId(localId); } + +ErrCode OsAccountManager::GetForegroundOsAccountLocalId(const uint64_t displayId, int32_t &localId) +{ + return IOsAccountManager::GetOrCreateOsAccountManager()->GetForegroundOsAccountLocalId(displayId, localId); +} } // namespace AccountSA } // namespace OHOS diff --git a/test/unittest/mock/os_account_manager_mock.h b/test/unittest/mock/os_account_manager_mock.h index bbaedbb89..3575e978b 100644 --- a/test/unittest/mock/os_account_manager_mock.h +++ b/test/unittest/mock/os_account_manager_mock.h @@ -26,6 +26,7 @@ public: virtual ~IOsAccountManager() = default; virtual ErrCode GetForegroundOsAccountLocalId(int32_t &localId) = 0; + virtual ErrCode GetForegroundOsAccountLocalId(const uint64_t displayId, int32_t &localId) = 0; static std::shared_ptr GetOrCreateOsAccountManager(); static void ReleaseAccountManager(); private: @@ -35,6 +36,7 @@ private: class OsAccountManagerMock : public IOsAccountManager { public: MOCK_METHOD(ErrCode, GetForegroundOsAccountLocalId, (int32_t &)); + MOCK_METHOD(ErrCode, GetForegroundOsAccountLocalId, (const uint64_t, int32_t &)); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/mock/softbus_connector_mock.cpp b/test/unittest/mock/softbus_connector_mock.cpp index 171311d9e..77c65ea49 100644 --- a/test/unittest/mock/softbus_connector_mock.cpp +++ b/test/unittest/mock/softbus_connector_mock.cpp @@ -39,5 +39,10 @@ DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &device { return DmSoftbusConnector::dmSoftbusConnector->GetDeviceInfoByDeviceId(deviceId); } + +std::shared_ptr SoftbusConnector::GetSoftbusSession() +{ + return DmSoftbusConnector::dmSoftbusConnector->GetSoftbusSession(); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_connector_mock.h b/test/unittest/mock/softbus_connector_mock.h index fa25cade0..a8caf1492 100644 --- a/test/unittest/mock/softbus_connector_mock.h +++ b/test/unittest/mock/softbus_connector_mock.h @@ -30,6 +30,7 @@ public: virtual bool CheckIsOnline(const std::string &targetDeviceId) = 0; virtual std::vector GetProcessInfo() = 0; virtual DmDeviceInfo GetDeviceInfoByDeviceId(const std::string &deviceId) = 0; + virtual std::shared_ptr GetSoftbusSession(); public: static inline std::shared_ptr dmSoftbusConnector = nullptr; }; @@ -40,6 +41,7 @@ public: MOCK_METHOD(bool, CheckIsOnline, (const std::string &)); MOCK_METHOD(std::vector, GetProcessInfo, ()); MOCK_METHOD(DmDeviceInfo, GetDeviceInfoByDeviceId, (const std::string &deviceId)); + MOCK_METHOD(std::shared_ptr, GetSoftbusSession, ()); }; } } diff --git a/test/unittest/mock/softbus_session_mock.cpp b/test/unittest/mock/softbus_session_mock.cpp index 1c657174e..c85d7045d 100644 --- a/test/unittest/mock/softbus_session_mock.cpp +++ b/test/unittest/mock/softbus_session_mock.cpp @@ -25,5 +25,20 @@ int32_t SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevI return DmSoftbusSession::dmSoftbusSession->GetPeerDeviceId(sessionId, peerDevId); } +int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) +{ + return DmSoftbusSession::dmSoftbusSession->SendData(sessionId, message); +} + +int32_t SoftbusSession::OpenAuthSessionWithPara(const std::string &deviceId, int32_t actionId, bool isEnable160m) +{ + return DmSoftbusSession::dmSoftbusSession->OpenAuthSessionWithPara(deviceId, actionId, isEnable160m); +} + +int32_t SoftbusSession::OpenAuthSession(const std::string &deviceId) +{ + return DmSoftbusSession::dmSoftbusSession->OpenAuthSession(deviceId); +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_session_mock.h b/test/unittest/mock/softbus_session_mock.h index 732174ef4..9f386d183 100644 --- a/test/unittest/mock/softbus_session_mock.h +++ b/test/unittest/mock/softbus_session_mock.h @@ -27,6 +27,10 @@ public: virtual ~DmSoftbusSession() = default; public: virtual int32_t GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) = 0; + virtual int32_t SendData(int32_t sessionId, std::string &message) = 0; + virtual int32_t OpenAuthSessionWithPara(const std::string &deviceId, int32_t actionId, bool isEnable160m) = 0; + virtual int32_t OpenAuthSession(const std::string &deviceId) = 0; + public: static inline std::shared_ptr dmSoftbusSession = nullptr; }; @@ -34,6 +38,9 @@ public: class SoftbusSessionMock : public DmSoftbusSession { public: MOCK_METHOD(int32_t, GetPeerDeviceId, (int32_t, std::string &)); + MOCK_METHOD(int32_t, SendData, (int32_t, std::string &)); + MOCK_METHOD(int32_t, OpenAuthSessionWithPara, (const std::string &, int32_t, bool)); + MOCK_METHOD(int32_t, OpenAuthSession, (const std::string &)); }; } } -- Gitee From 942771f2f1f06d58f4221d643eb63c08e19b91b1 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sun, 6 Apr 2025 11:58:08 +0800 Subject: [PATCH 3/8] add display code Signed-off-by: hwzhangchuang --- display/AppScope/app.json | 4 ++-- .../ets/UIExtAbility/ConfirmUIExtAbility.ets | 3 +++ .../ets/UIExtAbility/InputUIExtAbility.ets | 3 +++ .../ets/UIExtAbility/PincodeUIExtAbility.ets | 3 +++ .../src/main/ets/pages/ConfirmDialog.ets | 19 ++++++++++++++++--- .../main/ets/pages/ConfirmDialogWearable.ets | 10 ++++++++-- .../src/main/ets/pages/InputPinDialog.ets | 10 ++++++++-- .../main/ets/pages/InputPinDialogWearable.ets | 10 ++++++++-- .../entry/src/main/ets/pages/PinDialog.ets | 18 +++++++++++++++--- .../src/main/ets/pages/PinDialogWearable.ets | 10 ++++++++-- 10 files changed, 74 insertions(+), 16 deletions(-) diff --git a/display/AppScope/app.json b/display/AppScope/app.json index 14c36944e..c7b1de6ab 100644 --- a/display/AppScope/app.json +++ b/display/AppScope/app.json @@ -2,8 +2,8 @@ "app": { "bundleName": "com.ohos.devicemanagerui", "vendor": "example", - "versionCode": 1000038, - "versionName": "1.0.38", + "versionCode": 1000039, + "versionName": "1.0.39", "icon": "$media:app_icon", "label": "$string:app_name", "minAPIVersion": 10, diff --git a/display/entry/src/main/ets/UIExtAbility/ConfirmUIExtAbility.ets b/display/entry/src/main/ets/UIExtAbility/ConfirmUIExtAbility.ets index 6b5055fe7..512d9660c 100644 --- a/display/entry/src/main/ets/UIExtAbility/ConfirmUIExtAbility.ets +++ b/display/entry/src/main/ets/UIExtAbility/ConfirmUIExtAbility.ets @@ -39,6 +39,9 @@ export default class ConfirmUIExtAbility extends UIExtensionAbility { if (want.parameters.hostPkgLabel) { AppStorage.setOrCreate('hostPkgLabel', want.parameters.hostPkgLabel); } + if (want.parameters.tokenId) { + AppStorage.setOrCreate('tokenId', want.parameters.tokenId); + } let param: Record = { 'session': session diff --git a/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets b/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets index 15a8081dc..07200108d 100644 --- a/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets +++ b/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets @@ -27,6 +27,9 @@ export default class InputUIExtAbility extends UIExtensionAbility { if (want.parameters && want.parameters.model) { AppStorage.setOrCreate('model', want.parameters.model); } + if (want.parameters && want.parameters.tokenId) { + AppStorage.setOrCreate('tokenId', want.parameters.tokenId); + } let param: Record = { 'session': session diff --git a/display/entry/src/main/ets/UIExtAbility/PincodeUIExtAbility.ets b/display/entry/src/main/ets/UIExtAbility/PincodeUIExtAbility.ets index ad4d9c6dd..c6fcd9d9e 100644 --- a/display/entry/src/main/ets/UIExtAbility/PincodeUIExtAbility.ets +++ b/display/entry/src/main/ets/UIExtAbility/PincodeUIExtAbility.ets @@ -24,6 +24,9 @@ export default class InputUIExtAbility extends UIExtensionAbility { if (want.parameters && want.parameters.pinCode) { AppStorage.setOrCreate('pinCode', want.parameters.pinCode); } + if (want.parameters && want.parameters.tokenId) { + AppStorage.setOrCreate('tokenId', want.parameters.tokenId); + } let param: Record = { 'session': session diff --git a/display/entry/src/main/ets/pages/ConfirmDialog.ets b/display/entry/src/main/ets/pages/ConfirmDialog.ets index d29860af2..55cc5c7ba 100644 --- a/display/entry/src/main/ets/pages/ConfirmDialog.ets +++ b/display/entry/src/main/ets/pages/ConfirmDialog.ets @@ -39,6 +39,7 @@ struct ConfirmCustomDialog { @State peerCustomDescription: string = ''; @State peerDeviceName: string = ''; @State peerDeviceType: number = 0; + @State tokenId: number = 0; @State secondsNum: number = 30; @State times: number = 0; @State isAvailableType: boolean = false; @@ -80,6 +81,11 @@ struct ConfirmCustomDialog { console.log('peerDeviceType is ' + this.peerDeviceType); } + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + this.times = setInterval(() => { console.info('devicemanagerui confirm dialog run seconds:' + this.secondsNum); this.secondsNum--; @@ -138,7 +144,8 @@ struct ConfirmCustomDialog { return; } try { - dmClass.setUserOperation(operation, 'extra'); + let paramJsonStr = `{"tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log(TAG + 'dmClass setUserOperation failed') } @@ -348,6 +355,7 @@ struct ConfirmCustomDialog { @Entry @Component struct dialogPlusPage { + @State tokenId: number = 0; dialogController: CustomDialogController = new CustomDialogController({ builder: ConfirmCustomDialog(), autoCancel: false, @@ -365,7 +373,11 @@ struct dialogPlusPage { console.log(TAG + 'deviceManager exist') return } - deviceManager.createDeviceManager('com.ohos.devicemanagerui.confirm', + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + deviceManager.createDeviceManager('com.ohos.devicemanagerui.confirm' + ' ' + this.tokenId, (err: Error, dm: deviceManager.DeviceManager) => { if (err) { console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + JSON.stringify(dm)) @@ -398,7 +410,8 @@ struct dialogPlusPage { return; } try { - dmClass.setUserOperation(operation, 'extra'); + let paramJsonStr = `{"tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log(TAG + 'dmClass setUserOperation failed') } diff --git a/display/entry/src/main/ets/pages/ConfirmDialogWearable.ets b/display/entry/src/main/ets/pages/ConfirmDialogWearable.ets index 62435a1ba..152c65370 100644 --- a/display/entry/src/main/ets/pages/ConfirmDialogWearable.ets +++ b/display/entry/src/main/ets/pages/ConfirmDialogWearable.ets @@ -34,6 +34,7 @@ struct Index { @State peerCustomDescription: string = ''; @State peerDeviceName: string = ''; @State peerDeviceType: number = 0; + @State tokenId: number = 0; @State secondsNum: number = 30; @State times: number = 0; @State isAvailableType: boolean = false; @@ -45,7 +46,11 @@ struct Index { console.log(TAG + 'deviceManager exist'); return; } - deviceManager.createDeviceManager('com.ohos.devicemanagerui.confirm', + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + deviceManager.createDeviceManager('com.ohos.devicemanagerui.confirm' + ' ' + this.tokenId, (err: Error, dm: deviceManager.DeviceManager) => { if (err) { console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + JSON.stringify(dm)); @@ -133,7 +138,8 @@ struct Index { } try { this.isUserOperate = true; - dmClass.setUserOperation(operation, 'extra'); + let paramJsonStr = `{"tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log(TAG + 'dmClass setUserOperation failed'); } diff --git a/display/entry/src/main/ets/pages/InputPinDialog.ets b/display/entry/src/main/ets/pages/InputPinDialog.ets index 1add1ade8..a04de966e 100644 --- a/display/entry/src/main/ets/pages/InputPinDialog.ets +++ b/display/entry/src/main/ets/pages/InputPinDialog.ets @@ -41,6 +41,7 @@ struct InputCustomDialog { @State errorTipsVisible: Visibility = Visibility.None; @State heightNum: number = 600; @State targetDeviceName: string = ''; + @State tokenId: number = 0; @State model: string = MODEL_PIN; @State isPC: boolean = false; @State btnColor: ResourceColor = Color.Transparent; @@ -80,7 +81,11 @@ struct InputCustomDialog { this.model = AppStorage.get('model') as string; console.log('model is ' + this.model); } - deviceManager.createDeviceManager('com.ohos.devicemanagerui.input', + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + deviceManager.createDeviceManager('com.ohos.devicemanagerui.input' + ' ' + this.tokenId, (err: Error, dm: deviceManager.DeviceManager) => { if (err) { console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + '${dm}'); @@ -179,7 +184,8 @@ struct InputCustomDialog { return; } try { - dmClass.setUserOperation(operation, extra); + let paramJsonStr = `{"pinCode": "${extra}", "tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log('dmClass setUserOperation failed'); } diff --git a/display/entry/src/main/ets/pages/InputPinDialogWearable.ets b/display/entry/src/main/ets/pages/InputPinDialogWearable.ets index 581575719..1f95a3cca 100644 --- a/display/entry/src/main/ets/pages/InputPinDialogWearable.ets +++ b/display/entry/src/main/ets/pages/InputPinDialogWearable.ets @@ -30,6 +30,7 @@ const MAX_PINCODE_LENGTH = 6; @Component struct Index { @State isTimes: number = 3; + @State tokenId: number = 0; @State passwordCircle: string[] = ['', '', '', '', '', '']; @State errorTips: Resource = $r('app.plural.dm_incorrect_code', this.isTimes, this.isTimes); @State @Watch('onChangeInput') input: string = ''; @@ -55,7 +56,11 @@ struct Index { console.log(TAG + 'deviceManager exist'); return; } - deviceManager.createDeviceManager('com.ohos.devicemanagerui.input', + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + deviceManager.createDeviceManager('com.ohos.devicemanagerui.input' + ' ' + this.tokenId, (err: Error, dm: deviceManager.DeviceManager) => { if (err) { console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + '${dm}'); @@ -132,7 +137,8 @@ struct Index { } try { this.isUserOperate = true; - dmClass.setUserOperation(operation, extra); + let paramJsonStr = `{"pinCode": ${extra}, "tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log('dmClass setUserOperation failed'); } diff --git a/display/entry/src/main/ets/pages/PinDialog.ets b/display/entry/src/main/ets/pages/PinDialog.ets index df0408e3a..0f0a58faf 100644 --- a/display/entry/src/main/ets/pages/PinDialog.ets +++ b/display/entry/src/main/ets/pages/PinDialog.ets @@ -28,6 +28,7 @@ const MSG_CANCEL_PIN_CODE_SHOW: number = 2; @CustomDialog struct PinCustomDialog { @State pinCode: string = ''; + @State tokenId: number = 0; @State pinCodeArr: Array = []; @State btnColor: ResourceColor = Color.Transparent; @State isPC: boolean = false; @@ -53,6 +54,10 @@ struct PinCustomDialog { this.pinCode = AppStorage.get('pinCode') as string; this.pinCodeArr = this.pinCode.split(''); console.log(TAG + 'this.pinCodeArr' + this.pinCodeArr); + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } } setUserOperation(operation: number) { @@ -62,7 +67,8 @@ struct PinCustomDialog { return; } try { - dmClass.setUserOperation(operation, 'extra'); + let paramJsonStr = `{"tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log(TAG + 'dmClass setUserOperation failed'); } @@ -176,6 +182,7 @@ struct PinCustomDialog { @Entry @Component struct dialogPlusPage { + @State tokenId: number = 0; dialogController: CustomDialogController = new CustomDialogController({ builder: PinCustomDialog(), cancel: this.onCancel, @@ -227,7 +234,11 @@ struct dialogPlusPage { console.log(TAG + 'deviceManager exist'); return; } - deviceManager.createDeviceManager('com.ohos.devicemanagerui.pin', + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + deviceManager.createDeviceManager('com.ohos.devicemanagerui.pin' + ' ' + this.tokenId, (err: Error, dm: deviceManager.DeviceManager) => { if (err) { console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + JSON.stringify(dm)) @@ -252,7 +263,8 @@ struct dialogPlusPage { return; } try { - dmClass.setUserOperation(operation, 'extra'); + let paramJsonStr = `{"tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log(TAG + 'dmClass setUserOperation failed') } diff --git a/display/entry/src/main/ets/pages/PinDialogWearable.ets b/display/entry/src/main/ets/pages/PinDialogWearable.ets index 58bf8acfd..8e9fd0b49 100644 --- a/display/entry/src/main/ets/pages/PinDialogWearable.ets +++ b/display/entry/src/main/ets/pages/PinDialogWearable.ets @@ -25,6 +25,7 @@ const MSG_CANCEL_PIN_CODE_SHOW: number = 2; @Component struct PinDialog { @State pinCode: string = ''; + @State tokenId: number = 0; @State pinCodeArr: Array = []; @State btnColor: ResourceColor = Color.Transparent; @State isUserOperate: boolean = false; @@ -83,7 +84,11 @@ struct PinDialog { console.log(TAG + 'deviceManager exist'); return; } - deviceManager.createDeviceManager('com.ohos.devicemanagerui.pin', + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + deviceManager.createDeviceManager('com.ohos.devicemanagerui.pin' + ' ' + this.tokenId, (err: Error, dm: deviceManager.DeviceManager) => { if (err) { console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + JSON.stringify(dm)); @@ -109,7 +114,8 @@ struct PinDialog { } try { this.isUserOperate = true; - dmClass.setUserOperation(operation, 'extra'); + let paramJsonStr = `{"tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log(TAG + 'dmClass setUserOperation failed'); } -- Gitee From 2eba69b29abece95d3ca8a9d558980408bb76f50 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sun, 6 Apr 2025 11:58:45 +0800 Subject: [PATCH 4/8] add other code Signed-off-by: hwzhangchuang --- bundle.json | 3 +- common/include/dm_error_type.h | 11 +- .../include/deviceprofile_connector.h | 46 +- .../include/multiple_user_connector.h | 5 +- .../src/deviceprofile_connector.cpp | 444 ++++++++++++++++-- .../src/multiple_user_connector.cpp | 39 +- 6 files changed, 484 insertions(+), 64 deletions(-) diff --git a/bundle.json b/bundle.json index 769e15000..aabf1cb47 100644 --- a/bundle.json +++ b/bundle.json @@ -59,7 +59,8 @@ "resource_management", "wifi", "screenlock_mgr", - "mbedtls" + "mbedtls", + "zlib" ], "third_party": [] }, diff --git a/common/include/dm_error_type.h b/common/include/dm_error_type.h index 2d2b96fe2..35cda6358 100644 --- a/common/include/dm_error_type.h +++ b/common/include/dm_error_type.h @@ -22,7 +22,7 @@ enum { DM_OK = 0, SOFTBUS_OK = 0, STOP_BIND = 1, - + DM_ALREADY_AUTHED = 2, /* Transfer to the other end device, not define specification error code */ ERR_DM_NOT_SYSTEM_APP = 202, ERR_DM_TIME_OUT = -20001, @@ -121,6 +121,15 @@ enum { ERR_DM_PROCESS_SESSION_KEY_FAILED = 96929833, ERR_DM_HILINKSVC_SCAS_CHECK_FAILED = 96929834, ERR_DM_FIND_NETWORKID_LIST_EMPTY = 96929835, + ERR_DM_GET_SESSION_KEY_FAILED = 96929836, + ERR_DM_QUADRUPLE_NOT_SAME = 96929837, + ERR_DM_NEXT_STATE_INVALID = 96929838, + ERR_DM_LOGIC_SESSION_CREATE_FAILED = 96929839, + ERR_DM_SESSION_CLOSED = 96929840, + ERR_DM_GET_LOCAL_USERID_FAILED = 969298341, + ERR_DM_CAPABILITY_NEGOTIATE_FAILED = 969298342, + ERR_DM_BIND_TRUST_TARGET = 969298343, + ERR_DM_BINDTARGET_SCREEN_LOCK = 969298344, }; } // namespace DistributedHardware } // namespace OHOS diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 64533caa1..f5c8b9631 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -36,14 +36,17 @@ EXPORT extern const uint32_t DEVICE_PEER_TO_PEER_TYPE; EXPORT extern const uint32_t DEVICE_ACROSS_ACCOUNT_TYPE; EXPORT extern const uint32_t IDENTICAL_ACCOUNT_TYPE; -EXPORT extern const uint32_t DM_IDENTICAL_ACCOUNT; -EXPORT extern const uint32_t DM_POINT_TO_POINT; -EXPORT extern const uint32_t DM_ACROSS_ACCOUNT; EXPORT extern const uint32_t DM_INVALIED_BINDTYPE; -EXPORT extern const uint32_t DEVICE; +EXPORT extern const uint32_t USER; EXPORT extern const uint32_t SERVICE; EXPORT extern const uint32_t APP; +const uint32_t DM_IDENTICAL_ACCOUNT = 1; +const uint32_t DM_SHARE = 2; +const uint32_t DM_LNN = 3; +const uint32_t DM_POINT_TO_POINT = 256; +const uint32_t DM_ACROSS_ACCOUNT = 1282; + enum ProfileState { INACTIVE = 0, ACTIVE = 1 @@ -89,6 +92,8 @@ typedef struct DmAccessee { typedef struct DmOfflineParam { uint32_t bindType; std::vector processVec; + std::vector credIdVec; + std::vector skIdVec; int32_t leftAclNumber; } DmOfflineParam; @@ -112,8 +117,12 @@ public: class DeviceProfileConnector : public IDeviceProfileConnector { DM_DECLARE_SINGLE_INSTANCE(DeviceProfileConnector); public: + EXPORT DmOfflineParam DeleteAccessControlListV2(uint32_t tokenId, const std::string &localDeviceId, + const std::string &remoteDeviceId, int32_t bindLevel, const std::string &extra); EXPORT std::vector GetAccessControlProfile(); + EXPORT DmOfflineParam HandleServiceUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, const std::string &localUdid, int32_t tokenId); std::vector GetAccessControlProfileByUserId(int32_t userId); std::vector GetAclProfileByDeviceIdAndUserId( const std::string &deviceId, int32_t userId); @@ -164,13 +173,12 @@ public: int32_t userId, const std::string &accountId, const std::string &localUdid); int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid); - EXPORT int32_t HandleDevUnBindEvent(int32_t remoteUserId, - const std::string &remoteUdid, const std::string &localUdid); - EXPORT OHOS::DistributedHardware::ProcessInfo HandleAppUnBindEvent( - int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid); - EXPORT OHOS::DistributedHardware::ProcessInfo HandleAppUnBindEvent( - int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid, - int32_t peerTokenId); + EXPORT int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + const std::string &localUdid, DmOfflineParam &offlineParam); + EXPORT DmOfflineParam HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId, const std::string &localUdid); + EXPORT DmOfflineParam HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId, const std::string &localUdid, int32_t peerTokenId); EXPORT std::vector GetAllAccessControlProfile(); EXPORT void DeleteAccessControlById(int64_t accessControlId); @@ -205,6 +213,7 @@ public: const std::vector &localUserIds, std::string &localUdid); EXPORT void HandleDeviceUnBind(int32_t bindType, const std::string &peerUdid, const std::string &localUdid, int32_t localUserId, const std::string &localAccountId); + EXPORT int32_t DeleteSessionKey(int32_t sessionKeyId); EXPORT int32_t SubscribeDeviceProfileInited( sptr dpInitedCallback); EXPORT int32_t UnSubscribeDeviceProfileInited(); @@ -228,6 +237,8 @@ public: int32_t HandleUserStop(int32_t stopUserId, const std::string &stopEventUdid); int32_t HandleUserStop(int32_t stopUserId, const std::string &localUdid, const std::vector &acceptEventUdids); + std::string IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid, + int32_t tokenId, int32_t userId); private: int32_t HandleDmAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); @@ -267,6 +278,19 @@ private: bool CheckAclStatusNotMatch(const DistributedDeviceProfile::AccessControlProfile &profile, const std::string &localUdid, const std::vector &foregroundUserIds, const std::vector &backgroundUserIds); + void DeleteAppBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid); + void DeleteAppBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid, const std::string &extra); + void DeleteServiceBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid); + std::string isAuthAppServiceNewVersion(std::string localUdid, std::string remoteUdid, int32_t tokenId, + int32_t userId, std::vector profiles); + std::string isAuthDeviceNewVersion(std::string localUdid, std::string remoteUdid, + std::vector profiles); }; extern "C" IDeviceProfileConnector *CreateDpConnectorInstance(); diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index a96752c43..8d24824d9 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -83,7 +83,7 @@ public: * @tc.type: FUNC */ static std::string GetSwitchOldAccountId(void); - + /** * @tc.name: MultipleUserConnector::SetSwitchOldAccountName * @tc.desc: Set Switch Old AccountName of the Multiple User Connector @@ -108,6 +108,7 @@ public: EXPORT static void SetAccountInfo(int32_t userId, DMAccountInfo dmAccountInfo); EXPORT static DMAccountInfo GetAccountInfoByUserId(int32_t userId); EXPORT static void DeleteAccountInfoByUserId(int32_t userId); + EXPORT static void GetTokenId(uint32_t &tokenId); EXPORT static void GetTokenIdAndForegroundUserId(uint32_t &tokenId, int32_t &userId); EXPORT static void GetCallerUserId(int32_t &userId); @@ -121,6 +122,8 @@ public: EXPORT static void ClearLockedUser(std::vector &foregroundUserVec, std::vector &backgroundUserVec); EXPORT static DMAccountInfo GetCurrentDMAccountInfo(); + EXPORT static void GetCallingTokenId(uint32_t &tokenId); + EXPORT static int32_t GetUserIdByDisplayId(uint64_t displayId); private: static int32_t oldUserId_; static std::string accountId_; diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 1146f3e8e..32043d6a6 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -13,6 +13,8 @@ * limitations under the License. */ +#include + #include "deviceprofile_connector.h" #include "crypto_mgr.h" #include "dm_anonymous.h" @@ -32,18 +34,262 @@ const uint32_t DEVICE_PEER_TO_PEER_TYPE = 3; const uint32_t DEVICE_ACROSS_ACCOUNT_TYPE = 4; const uint32_t IDENTICAL_ACCOUNT_TYPE = 5; -const uint32_t DM_IDENTICAL_ACCOUNT = 1; -const uint32_t DM_POINT_TO_POINT = 256; -const uint32_t DM_ACROSS_ACCOUNT = 1282; const uint32_t DM_INVALIED_BINDTYPE = 2048; -const uint32_t DEVICE = 1; const uint32_t SERVICE = 2; const uint32_t APP = 3; +const uint32_t USER = 1; constexpr uint32_t MAX_SESSION_KEY_LENGTH = 512; namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(DeviceProfileConnector); +std::string DeviceProfileConnector::IsAuthNewVersion(int32_t bindLevel, std::string localUdid, std::string remoteUdid, + int32_t tokenId, int32_t userId) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); + if (static_cast(bindLevel) > APP || static_cast(bindLevel) < USER) { + LOGE("Invalied bindlevel bindLevel=%{public}u.", bindLevel); + return ""; + } + std::vector profiles = GetAclProfileByDeviceIdAndUserId(localUdid, userId); + if (profiles.empty()) { + LOGE("Acl is empty."); + return ""; + } + switch (bindLevel) { + case APP: + case SERVICE: + return isAuthAppServiceNewVersion(localUdid, remoteUdid, tokenId, userId, profiles); + case USER: + return isAuthDeviceNewVersion(localUdid, remoteUdid, profiles); + default: + break; + } + return ""; +} + +std::string DeviceProfileConnector::isAuthAppServiceNewVersion(std::string localUdid, std::string remoteUdid, + int32_t tokenId, int32_t userId, std::vector profiles) +{ + for (auto &item : profiles) { + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != APP || item.GetBindLevel() != SERVICE) { + continue; + } + int32_t acerUserId = item.GetAccesser().GetAccesserUserId(); + int32_t aceeUserId = item.GetAccessee().GetAccesseeUserId(); + std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + int32_t acerTokenId = static_cast(item.GetAccesser().GetAccesserTokenId()); + int32_t aceeTokenId = static_cast(item.GetAccessee().GetAccesseeTokenId()); + if (acerUserId == userId && acerTokenId == tokenId && + acerDeviceId == localUdid && aceeDeviceId == remoteUdid) { + return item.GetAccesser().GetAccesserExtraData(); + } + if (aceeUserId == userId && aceeTokenId == tokenId && + aceeDeviceId == localUdid && acerDeviceId == remoteUdid) { + return item.GetAccessee().GetAccesseeExtraData(); + } + } + return ""; +} + +std::string DeviceProfileConnector::isAuthDeviceNewVersion(std::string localUdid, std::string remoteUdid, + std::vector profiles) +{ + for (auto &item : profiles) { + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != USER) { + continue; + } + std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + if (acerDeviceId == localUdid && aceeDeviceId == remoteUdid) { + return item.GetAccesser().GetAccesserExtraData(); + } + if (aceeDeviceId == localUdid && acerDeviceId == remoteUdid) { + return item.GetAccessee().GetAccesseeExtraData(); + } + } + return ""; +} +EXPORT DmOfflineParam DeviceProfileConnector::DeleteAccessControlListV2(uint32_t tokenId, + const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel, const std::string &extra) +{ + LOGI("localDeviceId %{public}s, remoteDeviceId %{public}s, bindLevel %{public}d.", + GetAnonyString(localDeviceId).c_str(), GetAnonyString(remoteDeviceId).c_str(), bindLevel); + DmOfflineParam offlineParam; + offlineParam.bindType = INVALIED_TYPE; + if (static_cast(bindLevel) > APP || static_cast(bindLevel) < USER) { + LOGE("Invalied bindlevel."); + return offlineParam; + } + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(localDeviceId, userId); + if (profiles.empty()) { + LOGE("Acl is empty."); + return offlineParam; + } + switch (bindLevel) { + case APP: + if (extra == "") { + DeleteAppBindLevelV2(offlineParam, tokenId, profiles, localDeviceId, remoteDeviceId); + } else { + DeleteAppBindLevelV2(offlineParam, tokenId, profiles, localDeviceId, remoteDeviceId, extra); + } + break; + case SERVICE: + DeleteServiceBindLevelV2(offlineParam, tokenId, profiles, localDeviceId, remoteDeviceId); + break; + case USER: + DeleteDeviceBindLevel(offlineParam, profiles, localDeviceId, remoteDeviceId); + break; + default: + LOGE("DeleteAccessControlListV2: Invalied bindlevel."); + break; + } + return offlineParam; +} + +void DeviceProfileConnector::DeleteAppBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid) +{ + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != APP) { + continue; + } + int64_t acerTokenId = item.GetAccesser().GetAccesserTokenId(); + int64_t aceeTokenId = item.GetAccessee().GetAccesseeTokenId(); + std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + if ((acerTokenId == static_cast(tokenId) || acerTokenId == 0) && + acerDeviceId == localUdid && aceeDeviceId == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + if ((aceeTokenId == static_cast(tokenId) || aceeTokenId == 0) && + aceeDeviceId == localUdid && acerDeviceId == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + } +} + +void DeviceProfileConnector::DeleteAppBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid, const std::string &extra) +{ + LOGI("DeviceProfileConnector::DeleteAppBindLevel extra %{public}s", extra.c_str()); + uint32_t peerTokenId = atoi(extra.c_str()); + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != APP) { + continue; + } + ProcessInfo processInfo; + int64_t acerTokenId = item.GetAccesser().GetAccesserTokenId(); + int64_t aceeTokenId = item.GetAccessee().GetAccesseeTokenId(); + std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + if ((acerTokenId == static_cast(tokenId) || acerTokenId == 0) && aceeDeviceId == remoteUdid && + (aceeTokenId == static_cast(peerTokenId) || aceeTokenId == 0) && acerDeviceId == localUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = APP; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + if ((aceeTokenId == static_cast(tokenId) || aceeTokenId == 0) && acerDeviceId == remoteUdid && + (acerTokenId == static_cast(peerTokenId) || acerTokenId == 0) && aceeDeviceId == localUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = APP; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + } +} + +void DeviceProfileConnector::DeleteServiceBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid) +{ + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != SERVICE) { + continue; + } + int64_t acerTokenId = item.GetAccesser().GetAccesserTokenId(); + int64_t aceeTokenId = item.GetAccessee().GetAccesseeTokenId(); + std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + if ((acerTokenId == static_cast(tokenId) || acerTokenId == 0) && + acerDeviceId == localUdid && aceeDeviceId == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = SERVICE; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + if ((aceeTokenId == static_cast(tokenId) || aceeTokenId == 0) && + aceeDeviceId == localUdid && acerDeviceId == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = SERVICE; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + } +} EXPORT std::vector DeviceProfileConnector::GetAccessControlProfile() { @@ -184,7 +430,7 @@ int32_t DeviceProfileConnector::GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, int32_t DeviceProfileConnector::CheckAuthForm(DmAuthForm form, AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo) { - if (profiles.GetBindLevel() == DEVICE || (profiles.GetBindLevel() == APP && discoveryInfo.pkgname == "")) { + if (profiles.GetBindLevel() == USER || (profiles.GetBindLevel() == APP && discoveryInfo.pkgname == "")) { return form; } if (profiles.GetBindLevel() == APP) { @@ -245,14 +491,14 @@ int32_t DeviceProfileConnector::GetAuthForm(DistributedDeviceProfile::AccessCont priority = IDENTICAL_ACCOUNT_TYPE; break; case DM_POINT_TO_POINT: - if (profiles.GetBindLevel() == DEVICE) { + if (profiles.GetBindLevel() == USER) { priority = DEVICE_PEER_TO_PEER_TYPE; } else if (profiles.GetBindLevel() == APP) { priority = APP_PEER_TO_PEER_TYPE; } break; case DM_ACROSS_ACCOUNT: - if (profiles.GetBindLevel() == DEVICE) { + if (profiles.GetBindLevel() == USER) { priority = DEVICE_ACROSS_ACCOUNT_TYPE; } else if (profiles.GetBindLevel() == APP) { priority = APP_ACROSS_ACCOUNT_TYPE; @@ -323,7 +569,7 @@ void DeviceProfileConnector::GetParamBindTypeVec(AccessControlProfile profile, s bindTypeVec.push_back(IDENTICAL_ACCOUNT_TYPE); break; case DM_POINT_TO_POINT: - if (profile.GetBindLevel() == DEVICE) { + if (profile.GetBindLevel() == USER) { bindTypeVec.push_back(DEVICE_PEER_TO_PEER_TYPE); } if (profile.GetBindLevel() == APP) { @@ -331,7 +577,7 @@ void DeviceProfileConnector::GetParamBindTypeVec(AccessControlProfile profile, s } break; case DM_ACROSS_ACCOUNT: - if (profile.GetBindLevel() == DEVICE) { + if (profile.GetBindLevel() == USER) { bindTypeVec.push_back(DEVICE_ACROSS_ACCOUNT_TYPE); } if (profile.GetBindLevel() == APP) { @@ -369,7 +615,7 @@ void DeviceProfileConnector::ProcessBindType(AccessControlProfile profiles, std: bindTypeIndex.push_back(index); } if (profiles.GetBindType() == DM_POINT_TO_POINT) { - if (profiles.GetBindLevel() == DEVICE) { + if (profiles.GetBindLevel() == USER) { sinkBindType.push_back(DEVICE_PEER_TO_PEER_TYPE); bindTypeIndex.push_back(index); } @@ -387,7 +633,7 @@ void DeviceProfileConnector::ProcessBindType(AccessControlProfile profiles, std: } } if (profiles.GetBindType() == DM_ACROSS_ACCOUNT) { - if (profiles.GetBindLevel() == DEVICE) { + if (profiles.GetBindLevel() == USER) { sinkBindType.push_back(DEVICE_ACROSS_ACCOUNT_TYPE); bindTypeIndex.push_back(index); } @@ -434,7 +680,7 @@ EXPORT std::vector DeviceProfileConnector::SyncAclByBindType( return bindType; } -EXPORT +EXPORT std::vector DeviceProfileConnector::GetProcessInfoFromAclByUserId( const std::string &localDeviceId, const std::string &targetDeviceId, int32_t userId) { @@ -574,13 +820,13 @@ EXPORT void DeviceProfileConnector::DeleteAclForRemoteUserRemoved( int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); if (accesserUdid == peerUdid && accesserUserId == peerUserId) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - if (item.GetBindLevel() == DEVICE) { + if (item.GetBindLevel() == USER) { userIds.push_back(accesseeUserId); } } if (accesseeUdid == peerUdid && accesseeUserId == peerUserId) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - if (item.GetBindLevel() == DEVICE) { + if (item.GetBindLevel() == USER) { userIds.push_back(accesserUserId); } } @@ -611,7 +857,7 @@ DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(const std::string pkgName.c_str(), GetAnonyString(localDeviceId).c_str(), GetAnonyString(remoteDeviceId).c_str(), bindLevel); DmOfflineParam offlineParam; offlineParam.bindType = INVALIED_TYPE; - if (static_cast(bindLevel) > APP || static_cast(bindLevel) < DEVICE) { + if (static_cast(bindLevel) > APP || static_cast(bindLevel) < USER) { LOGE("Invalied bindlevel."); return offlineParam; } @@ -632,7 +878,7 @@ DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(const std::string case SERVICE: DeleteServiceBindLevel(offlineParam, pkgName, profiles, localDeviceId, remoteDeviceId); break; - case DEVICE: + case USER: DeleteDeviceBindLevel(offlineParam, profiles, localDeviceId, remoteDeviceId); break; default: @@ -677,7 +923,7 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); - LOGI("Sink delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + LOGI("Sink delete acl pkgName %{public}s, bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; @@ -727,7 +973,7 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); - LOGI("Sink delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + LOGI("Sink delete acl pkgName %{public}s, bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; @@ -750,7 +996,9 @@ void DeviceProfileConnector::DeleteDeviceBindLevel(DmOfflineParam &offlineParam, item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; - offlineParam.bindType = DEVICE; + offlineParam.bindType = USER; + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; @@ -759,8 +1007,10 @@ void DeviceProfileConnector::DeleteDeviceBindLevel(DmOfflineParam &offlineParam, item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; - offlineParam.bindType = DEVICE; - LOGI("Sink delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + offlineParam.bindType = USER; + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; } @@ -796,7 +1046,7 @@ void DeviceProfileConnector::DeleteServiceBindLevel(DmOfflineParam &offlineParam DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = SERVICE; - LOGI("Sink delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + LOGI("Sink delete acl pkgName %{public}s, bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; @@ -836,7 +1086,7 @@ EXPORT bool DeviceProfileConnector::CheckSrcDevIdInAclForDevBind( LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { if (item.GetTrustDeviceId() == deviceId && item.GetStatus() == ACTIVE && - item.GetBindLevel() == DEVICE && (item.GetAccessee().GetAccesseeBundleName() == pkgName || + item.GetBindLevel() == USER && (item.GetAccessee().GetAccesseeBundleName() == pkgName || item.GetAccesser().GetAccesserBundleName() == "") && item.GetAccessee().GetAccesseeUserId() == 0 && item.GetAccessee().GetAccesseeAccountId() == "") { return true; @@ -851,7 +1101,7 @@ bool DeviceProfileConnector::CheckSinkDevIdInAclForDevBind(const std::string &pk LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { if (item.GetTrustDeviceId() == deviceId && item.GetStatus() == ACTIVE && - item.GetBindLevel() == DEVICE && (item.GetAccesser().GetAccesserBundleName() == pkgName || + item.GetBindLevel() == USER && (item.GetAccesser().GetAccesserBundleName() == pkgName || item.GetAccesser().GetAccesserBundleName() == "") && item.GetAccesser().GetAccesserUserId() == 0 && item.GetAccesser().GetAccesserAccountId() == "") { return true; @@ -1018,7 +1268,7 @@ bool DeviceProfileConnector::SingleUserProcess(const DistributedDeviceProfile::A ret = true; break; case DM_POINT_TO_POINT: - if (profile.GetBindLevel() == DEVICE || profile.GetBindLevel() == SERVICE) { + if (profile.GetBindLevel() == USER || profile.GetBindLevel() == SERVICE) { ret = true; } else if (profile.GetBindLevel() == APP && (profile.GetAccesser().GetAccesserBundleName() == caller.pkgName || @@ -1027,7 +1277,7 @@ bool DeviceProfileConnector::SingleUserProcess(const DistributedDeviceProfile::A } break; case DM_ACROSS_ACCOUNT: - if (profile.GetBindLevel() == DEVICE || profile.GetBindLevel() == SERVICE) { + if (profile.GetBindLevel() == USER || profile.GetBindLevel() == SERVICE) { ret = true; } else if (profile.GetBindLevel() == APP && (profile.GetAccesser().GetAccesserBundleName() == caller.pkgName || @@ -1204,8 +1454,8 @@ int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, return bindType; } -EXPORT int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, - const std::string &remoteUdid, const std::string &localUdid) +EXPORT int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + const std::string &localUdid, DmOfflineParam &offlineParam) { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), GetAnonyString(localUdid).c_str()); @@ -1219,85 +1469,170 @@ EXPORT int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId bindType = DM_IDENTICAL_ACCOUNT; continue; } - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - bindType = std::min(bindType, static_cast(item.GetBindType())); + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = USER; + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); + bindType = std::min(bindType, static_cast(item.GetBindType())); + continue; + } + if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = USER; + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + LOGI("Sink delete acl bindType %{public}u, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); + bindType = std::min(bindType, static_cast(item.GetBindType())); + continue; + } } return bindType; } -EXPORT OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEvent( - int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) +EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); - ProcessInfo processInfo; + std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId); + DmOfflineParam offlineParam; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != APP) { continue; } + ProcessInfo processInfo; if (item.GetAccesser().GetAccesserUserId() == remoteUserId && item.GetAccesser().GetAccesserDeviceId() == remoteUdid && - static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId && + (static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId || + static_cast(item.GetAccesser().GetAccesserTokenId()) == 0) && item.GetAccessee().GetAccesseeDeviceId() == localUdid) { LOGI("Src device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = APP; processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); continue; } if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && - static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId && + (static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId || + static_cast(item.GetAccessee().GetAccesseeTokenId()) == 0) && item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Sink device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = APP; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); continue; } } - return processInfo; + return offlineParam; } -EXPORT OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEvent( - int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, - const std::string &localUdid, int32_t peerTokenId) +EXPORT DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid, int32_t peerTokenId) { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); - ProcessInfo processInfo; + std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId); + DmOfflineParam offlineParam; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != APP) { continue; } + int32_t acerUserId = item.GetAccesser().GetAccesserUserId(); + int32_t aceeUserId = item.GetAccessee().GetAccesseeUserId(); + std::string acerDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string aceeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + int32_t acerTokenId = static_cast(item.GetAccesser().GetAccesserTokenId()); + int32_t aceeTokenId = static_cast(item.GetAccessee().GetAccesseeTokenId()); + ProcessInfo processInfo; + if (acerUserId == remoteUserId && acerDeviceId == remoteUdid && aceeDeviceId == localUdid && + (acerTokenId == tokenId || acerTokenId == 0) && (aceeTokenId == peerTokenId || aceeTokenId == 0)) { + LOGI("Src device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = APP; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); + continue; + } + if (aceeUserId == remoteUserId && aceeDeviceId == remoteUdid && acerDeviceId == localUdid && + (aceeTokenId == tokenId || aceeTokenId == 0) && (acerTokenId == peerTokenId || acerTokenId == 0)) { + LOGI("Sink device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = APP; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); + continue; + } + } + return offlineParam; +} + +DmOfflineParam DeviceProfileConnector::HandleServiceUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, const std::string &localUdid, int32_t tokenId) +{ + LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", + remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId); + DmOfflineParam offlineParam; + for (const auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != SERVICE) { + continue; + } if (item.GetAccesser().GetAccesserUserId() == remoteUserId && item.GetAccesser().GetAccesserDeviceId() == remoteUdid && - static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId && - static_cast(item.GetAccessee().GetAccesseeTokenId()) == peerTokenId && + (static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId || + static_cast(item.GetAccesser().GetAccesserTokenId()) == 0) && item.GetAccessee().GetAccesseeDeviceId() == localUdid) { LOGI("Src device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = SERVICE; + ProcessInfo processInfo; processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialIdStr()); continue; } if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && - static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId && - static_cast(item.GetAccesser().GetAccesserTokenId()) == peerTokenId && + (static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId || + static_cast(item.GetAccessee().GetAccesseeTokenId()) == 0) && item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Sink device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + offlineParam.bindType = SERVICE; + ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialIdStr()); continue; } } - return processInfo; + return offlineParam; } EXPORT std::vector DeviceProfileConnector::GetAllAccessControlProfile() @@ -1454,7 +1789,7 @@ std::vector DeviceProfileConnector::GetOfflineProcessInfo(std::stri processInfos.push_back(processInfo); } } - if (bindLevel == INVALIED_TYPE || bindLevel == DEVICE) { + if (bindLevel == INVALIED_TYPE || bindLevel == USER) { processInfos.clear(); for (const auto &item : localUserIds) { ProcessInfo processInfo; @@ -1738,7 +2073,7 @@ EXPORT int32_t DeviceProfileConnector::CheckDeviceInfoPermission( std::vector profiles = GetAccessControlProfileByUserId(localUserId); for (auto &item : profiles) { if (item.GetTrustDeviceId() == peerDeviceId) { - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() == DEVICE) { + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() == USER) { return DM_OK; } } @@ -1844,6 +2179,17 @@ int32_t DeviceProfileConnector::PutSessionKey(const std::vector & return DM_OK; } +int32_t DeviceProfileConnector::DeleteSessionKey(int32_t sessionKeyId) +{ + uint32_t userId = static_cast(MultipleUserConnector::GetCurrentAccountUserID()); + int32_t ret = DistributedDeviceProfileClient::GetInstance().DeleteSessionKey(userId, sessionKeyId); + if (ret != DM_OK) { + LOGE("failed: %{public}d", ret); + return ret; + } + return DM_OK; +} + bool DeviceProfileConnector::CheckAclStatusNotMatch(const DistributedDeviceProfile::AccessControlProfile &profile, const std::string &localUdid, const std::vector &foregroundUserIds, const std::vector &backgroundUserIds) diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index 1bcaa8d8e..6f0a0d5a4 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -122,6 +122,15 @@ void MultipleUserConnector::GetTokenIdAndForegroundUserId(uint32_t &tokenId, int userId = GetFirstForegroundUserId(); } +EXPORT void MultipleUserConnector::GetTokenId(uint32_t &tokenId) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); +#else + (void)tokenId; +#endif +} + void MultipleUserConnector::GetCallerUserId(int32_t &userId) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -363,12 +372,40 @@ EXPORT void MultipleUserConnector::ClearLockedUser( } } -DMAccountInfo MultipleUserConnector::GetCurrentDMAccountInfo() +EXPORT DMAccountInfo MultipleUserConnector::GetCurrentDMAccountInfo() { DMAccountInfo dmAccountInfo; dmAccountInfo.accountId = GetOhosAccountId(); dmAccountInfo.accountName = GetOhosAccountName(); return dmAccountInfo; } + +EXPORT void MultipleUserConnector::GetCallingTokenId(uint32_t &tokenId) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); +#else + (void)tokenId; +#endif +} + +EXPORT int32_t MultipleUserConnector::GetUserIdByDisplayId(uint64_t displayId) +{ + LOGI("displayId %{public}" PRIu64, displayId); + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + if (displayId == 0) { + userId = GetFirstForegroundUserId(); + return userId; + } +#ifdef OS_ACCOUNT_PART_EXISTS + int32_t ret = OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(displayId, userId); + if (ret != DM_OK) { + LOGE("GetForegroundOsAccountLocalId failed ret %{public}d.", ret); + } +#endif // OS_ACCOUNT_PART_EXISTS +#endif + return userId; +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From 166dfbac5a1260362d12c22811b31e4ddcc0f2d6 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sun, 6 Apr 2025 13:05:01 +0800 Subject: [PATCH 5/8] modify fun name Signed-off-by: hwzhangchuang --- commondependency/include/deviceprofile_connector.h | 4 ++-- commondependency/src/deviceprofile_connector.cpp | 8 ++++---- .../implementation/src/device_manager_service_impl.cpp | 1 - 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index f5c8b9631..197c053bd 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -287,9 +287,9 @@ private: void DeleteServiceBindLevelV2(DmOfflineParam &offlineParam, const uint32_t tokenId, const std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid); - std::string isAuthAppServiceNewVersion(std::string localUdid, std::string remoteUdid, int32_t tokenId, + std::string GetAppServiceAuthVersionInfo(std::string localUdid, std::string remoteUdid, int32_t tokenId, int32_t userId, std::vector profiles); - std::string isAuthDeviceNewVersion(std::string localUdid, std::string remoteUdid, + std::string GetDeviceAuthVersionInfo(std::string localUdid, std::string remoteUdid, std::vector profiles); }; diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 32043d6a6..9b27708cd 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -60,16 +60,16 @@ std::string DeviceProfileConnector::IsAuthNewVersion(int32_t bindLevel, std::str switch (bindLevel) { case APP: case SERVICE: - return isAuthAppServiceNewVersion(localUdid, remoteUdid, tokenId, userId, profiles); + return GetAppServiceAuthVersionInfo(localUdid, remoteUdid, tokenId, userId, profiles); case USER: - return isAuthDeviceNewVersion(localUdid, remoteUdid, profiles); + return GetDeviceAuthVersionInfo(localUdid, remoteUdid, profiles); default: break; } return ""; } -std::string DeviceProfileConnector::isAuthAppServiceNewVersion(std::string localUdid, std::string remoteUdid, +std::string DeviceProfileConnector::GetAppServiceAuthVersionInfo(std::string localUdid, std::string remoteUdid, int32_t tokenId, int32_t userId, std::vector profiles) { for (auto &item : profiles) { @@ -95,7 +95,7 @@ std::string DeviceProfileConnector::isAuthAppServiceNewVersion(std::string local return ""; } -std::string DeviceProfileConnector::isAuthDeviceNewVersion(std::string localUdid, std::string remoteUdid, +std::string DeviceProfileConnector::GetDeviceAuthVersionInfo(std::string localUdid, std::string remoteUdid, std::vector profiles) { for (auto &item : profiles) { diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index b0ce662dc..cb46715ca 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -730,7 +730,6 @@ static bool IsAuthManagerSourceByMessage(int32_t msgType) return msgType == MSG_TYPE_RESP_ACL_NEGOTIATE; } - // Get the current session object std::shared_ptr DeviceManagerServiceImpl::GetCurSession(int sessionId) { -- Gitee From f78fd82f1d6cad6ae6dc6d67eaf0dfd3f15cb8ad Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Sun, 6 Apr 2025 15:59:55 +0800 Subject: [PATCH 6/8] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8Dlanguage=E4=B8=BA?= =?UTF-8?q?=E7=A9=BA=E5=92=8C=E9=BB=84=E5=8C=BA=E6=97=A5=E5=BF=97=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: guoliang47 --- common/src/ipc/standard/ipc_model_codec.cpp | 2 +- .../include/i18n/dm_language_manager.h | 2 + .../auth_stages/auth_negotiate.cpp | 3 +- .../src/i18n/dm_language_manager.cpp | 50 +++++++++++++++++++ 4 files changed, 54 insertions(+), 3 deletions(-) diff --git a/common/src/ipc/standard/ipc_model_codec.cpp b/common/src/ipc/standard/ipc_model_codec.cpp index 1091961c6..daf2d650d 100644 --- a/common/src/ipc/standard/ipc_model_codec.cpp +++ b/common/src/ipc/standard/ipc_model_codec.cpp @@ -462,7 +462,7 @@ bool IpcModelCodec::DecodeStringVector(MessageParcel &parcel, std::vector MAX_DEVICE_PROFILE_SIZE) { - LOGE("num is Invalid value, num = %{public}zu", num); + LOGE("num is Invalid value, num = %{public}" PRIu32, num); return false; } for (uint32_t k = 0; k < num; k++) { diff --git a/services/implementation/include/i18n/dm_language_manager.h b/services/implementation/include/i18n/dm_language_manager.h index 74b0ca886..5a39f1aac 100644 --- a/services/implementation/include/i18n/dm_language_manager.h +++ b/services/implementation/include/i18n/dm_language_manager.h @@ -31,9 +31,11 @@ public: DmLanguageManager() {} ~DmLanguageManager() {} std::string GetSystemParam(const std::string &key); + std::string GetSystemLanguage(); void GetLocaleByLanguage(const std::string &language, std::set &localeSet); std::string GetTextBySystemLocale(const cJSON *const textObj, const std::set &localeSet); std::string GetTextBySystemLanguage(const std::string &text); + std::string GetTextByLanguage(const std::string &text, const std::string &language); }; } // namespace DistributedHardware } // namespace OHOS 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 12db712f6..babade2b3 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -45,7 +45,6 @@ using namespace OHOS::Security::AccessToken; namespace OHOS { namespace DistributedHardware { -const std::string SYSTEM_LANGUAGE_KEY = "persist.global.language"; #ifdef DEVICE_MANAGER_COMMON_FLAG constexpr int32_t PROCESS_NAME_WHITE_LIST_NUM = 1; @@ -163,7 +162,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->accesser.language = DmLanguageManager::GetInstance().GetSystemParam(SYSTEM_LANGUAGE_KEY); + context->accessee.language = DmLanguageManager::GetInstance().GetSystemLanguage(); context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); return DM_OK; diff --git a/services/implementation/src/i18n/dm_language_manager.cpp b/services/implementation/src/i18n/dm_language_manager.cpp index 3357cd49b..2ecf862e4 100644 --- a/services/implementation/src/i18n/dm_language_manager.cpp +++ b/services/implementation/src/i18n/dm_language_manager.cpp @@ -144,5 +144,55 @@ std::string DmLanguageManager::GetTextBySystemLocale(const cJSON *const textObj, } return ""; } + +std::string DmLanguageManager::GetSystemLanguage() +{ + std::string language = GetSystemParam(SYSTEM_LANGUAGE_KEY); + if (!language.empty()) { + return language; + } + + language = GetSystemParam(SYSTEM_LANGUAGE_LOCALE_KEY); + if (!language.empty()) { + return language; + } + + return DEFAULT_LANGUAGE; +} + +std::string DmLanguageManager::GetTextByLanguage(const std::string &text, const std::string &language) +{ + if (text.empty()) { + return ""; + } + cJSON *textObj = cJSON_Parse(text.c_str()); + if (textObj == NULL) { + LOGE("parse text failed"); + return text; + } + std::string resultText = text; + + cJSON *languageJson = cJSON_GetObjectItem(textObj, language.c_str()); + if (languageJson != NULL && cJSON_IsString(languageJson)) { + resultText = std::string(languageJson->valuestring); + cJSON_Delete(textObj); + return resultText; + } + cJSON *defaultJson = cJSON_GetObjectItem(textObj, DEFAULT_LANGUAGE.c_str()); + if (defaultJson != NULL && cJSON_IsString(defaultJson)) { + resultText = std::string(defaultJson->valuestring); + cJSON_Delete(textObj); + return resultText; + } + cJSON *enJson = cJSON_GetObjectItem(textObj, LANGUAGE_EN.c_str()); + if (enJson != NULL && cJSON_IsString(enJson)) { + resultText = std::string(enJson->valuestring); + cJSON_Delete(textObj); + return resultText; + } + cJSON_Delete(textObj); + return ""; +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From 6924b7603e6579330d93d4f2da9be7f877f291fa Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Sun, 6 Apr 2025 17:27:06 +0800 Subject: [PATCH 7/8] fix: codecheck Signed-off-by: ZHANGHE24 --- .../include/authentication_v2/dm_auth_state.h | 8 +-- .../authentication_v2/dm_negotiate_process.h | 9 +-- .../auth_stages/auth_confirm.cpp | 63 +++---------------- .../auth_stages/auth_negotiate.cpp | 54 +--------------- .../src/authentication_v2/dm_auth_state.cpp | 56 +++++++++++++++++ 5 files changed, 72 insertions(+), 118 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index f5af9a12d..0dfe11e93 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -159,6 +159,9 @@ protected: bool NeedReqUserConfirm(std::shared_ptr context); bool NeedAgreeCredential(std::shared_ptr context); bool NeedAgreeAcl(std::shared_ptr context); + uint32_t GetCredType(std::shared_ptr context, const JsonItemObject &credInfo); + uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo); + bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); }; class AuthSrcConfirmState : public DmAuthState { @@ -173,7 +176,6 @@ private: void GetIdenticalCredentialInfo(std::shared_ptr context, JsonObject &credInfo); void GetShareCredentialInfo(std::shared_ptr context, JsonObject &credInfo); void GetP2PCredentialInfo(std::shared_ptr context, JsonObject &credInfo); - uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo); void GetSrcAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo); bool IdenticalAccountAclCompare(std::shared_ptr context, const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); @@ -186,7 +188,6 @@ private: bool CheckCredIdInAcl(const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType); void GetSrcCredType(std::shared_ptr context, JsonObject &credInfo, JsonObject &credTypeJson); - bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); }; class AuthSinkStatePinAuthComm { @@ -396,7 +397,6 @@ private: void GetIdenticalCredentialInfo(std::shared_ptr context, JsonObject &credInfo); void GetShareCredentialInfo(std::shared_ptr context, JsonObject &credInfo); void GetP2PCredentialInfo(std::shared_ptr context, JsonObject &credInfo); - uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo); void GetSinkAclInfo(std::shared_ptr context, JsonObject &credInfo, JsonObject &aclInfo); bool IdenticalAccountAclCompare(std::shared_ptr context, const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); @@ -409,8 +409,6 @@ private: bool CheckCredIdInAcl(const DistributedDeviceProfile::AccessControlProfile &profile, JsonObject &credInfo, uint32_t bindType); void GetSinkCredType(std::shared_ptr context, JsonObject &credInfo, JsonObject &credTypeJson); - bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); - }; class AuthSinkDataSyncState : public DmAuthState { diff --git a/services/implementation/include/authentication_v2/dm_negotiate_process.h b/services/implementation/include/authentication_v2/dm_negotiate_process.h index 4a58433a1..f8a21a9f0 100644 --- a/services/implementation/include/authentication_v2/dm_negotiate_process.h +++ b/services/implementation/include/authentication_v2/dm_negotiate_process.h @@ -47,12 +47,13 @@ public: CredType credType; AclType aclType; AuthType authType; - - NegotiateSpec(CredType credTypeTemp, AclType aclTypeTemp, AuthType authTypeTemp) + + NegotiateSpec(CredType credTypeTemp, AclType aclTypeTemp, AuthType authTypeTemp) : credType(credTypeTemp), aclType(aclTypeTemp), authType(authTypeTemp) {} - + // 重载<运算符用于map排序 - bool operator<(const NegotiateSpec& other) const { + bool operator<(const NegotiateSpec& other) const + { if (credType != other.credType) return credType < other.credType; if (aclType != other.aclType) return aclType < other.aclType; return authType < other.authType; 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 dfadeafa5..48f8c8dce 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -70,7 +70,8 @@ void AuthSrcConfirmState::NegotiateCredential(std::shared_ptr con LOGI("have share credential."); credTypeNegoResult["shareCredType"] = DM_SHARE; } - if (accesseeCredTypeList.Contains("pointTopointCredType") && accesserCredTypeList.Contains("pointTopointCredType")) { + if (accesseeCredTypeList.Contains("pointTopointCredType") && + accesserCredTypeList.Contains("pointTopointCredType")) { LOGI("have point_to_point credential."); credTypeNegoResult["pointTopointCredType"] = DM_POINT_TO_POINT; } @@ -319,7 +320,7 @@ void AuthSrcConfirmState::GetSrcCredentialInfo(std::shared_ptr co continue; } JsonItemObject credInfoTemp = item[key]; - uint32_t credType = GetCredentialType(context, credInfoTemp); + uint32_t credType = DmAuthState::GetCredentialType(context, credInfoTemp); if (credType == DM_INVALIED_BINDTYPE || !credInfoTemp.Contains(FILED_CRED_TYPE) || !credInfoTemp[FILED_CRED_TYPE].IsNumberInteger()) { deleteCredInfo.push_back(key); @@ -333,58 +334,6 @@ void AuthSrcConfirmState::GetSrcCredentialInfo(std::shared_ptr co } } -uint32_t AuthSrcConfirmState::GetCredentialType(std::shared_ptr context, - const JsonItemObject &credInfo) -{ - CHECK_NULL_RETURN(context, DM_INVALIED_BINDTYPE); - if (!credInfo.Contains(FILED_CRED_TYPE) || !credInfo[FILED_CRED_TYPE].IsNumberInteger() || - !credInfo.Contains(FILED_AUTHORIZED_SCOPE) || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumberInteger() || - !credInfo.Contains(FILED_SUBJECT) || !credInfo[FILED_SUBJECT].IsNumberInteger()) { - LOGE("credType or authorizedScope invalid."); - return DM_INVALIED_BINDTYPE; - } - int32_t credType = credInfo[FILED_CRED_TYPE].Get(); - int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); - int32_t subject = credInfo[FILED_SUBJECT].Get(); - std::vector appList; - credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); - if (credType == ACCOUNT_RELATED && authorizedScope == SCOPE_USER) { - return DM_IDENTICAL_ACCOUNT; - } - if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && - context->direction == DM_AUTH_SOURCE && subject == SUBJECT_PRIMARY) { - return DM_SHARE; - } - if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && - context->direction == DM_AUTH_SINK && subject == SUBJECT_SECONDARY) { - return DM_SHARE; - } - if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { - return DM_POINT_TO_POINT; - } - if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_USER && appList.empty()) { - return DM_LNN; - } - return DM_INVALIED_BINDTYPE; -} - -bool AuthSrcConfirmState::HaveSameTokenId(std::shared_ptr context, - const std::vector &tokenList) -{ - // Store the token of src and sink. The size must be 2. - if (tokenList.size() != 2) { - LOGE("HaveSameTokenId invalid tokenList size."); - return false; - } - - // tokenIdList = [srcTokenId, sinkTokenId] - std::string srcTokenIdHash = Crypto::Sha256(tokenList[0]); - std::string sinkTokenIdHash = Crypto::Sha256(tokenList[1]); - - return (srcTokenIdHash == context->accesser.tokenIdHash) && - (sinkTokenIdHash == context->accessee.tokenIdHash); -} - void AuthSrcConfirmState::GetIdenticalCredentialInfo(std::shared_ptr context, JsonObject &credInfo) { @@ -520,7 +469,8 @@ void AuthSinkConfirmState::NegotiateCredential(std::shared_ptr co LOGI("have share credential."); credTypeNegoResult["shareCredType"] = DM_SHARE; } - if (accesseeCredTypeList.Contains("pointTopointCredType") && accesserCredTypeList.Contains("pointTopointCredType")) { + if (accesseeCredTypeList.Contains("pointTopointCredType") && + accesserCredTypeList.Contains("pointTopointCredType")) { LOGI("have point_to_point credential."); credTypeNegoResult["pointTopointCredType"] = DM_POINT_TO_POINT; } @@ -634,7 +584,8 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) context->accesser.credTypeList = credTypeNegoResult.Dump(); context->accesser.aclList = aclNegoResult.Dump(); NegotiateAcl(context, aclNegoResult); - if (credTypeNegoResult.Dump() != context->accesser.credTypeList || aclNegoResult.Dump() != context->accesser.aclList) { + if (credTypeNegoResult.Dump() != context->accesser.credTypeList || + aclNegoResult.Dump() != context->accesser.aclList) { LOGE("compability negotiate not match."); context->reason = ERR_DM_CAPABILITY_NEGOTIATE_FAILED; return ERR_DM_FAILED; 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 babade2b3..9c880bcdf 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -429,7 +429,7 @@ void AuthSinkNegotiateStateMachine::GetSinkCredentialInfo(std::shared_ptr context, - const JsonItemObject &credInfo) -{ - CHECK_NULL_RETURN(context, DM_INVALIED_BINDTYPE); - if (!credInfo.Contains(FILED_CRED_TYPE) || !credInfo[FILED_CRED_TYPE].IsNumberInteger() || - !credInfo.Contains(FILED_AUTHORIZED_SCOPE) || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumberInteger() || - !credInfo.Contains(FILED_SUBJECT) || !credInfo[FILED_SUBJECT].IsNumberInteger()) { - LOGE("credType or authorizedScope invalid."); - return DM_INVALIED_BINDTYPE; - } - int32_t credType = credInfo[FILED_CRED_TYPE].Get(); - int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); - int32_t subject = credInfo[FILED_SUBJECT].Get(); - std::vector appList; - credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); - if (credType == ACCOUNT_RELATED && authorizedScope == SCOPE_USER) { - return DM_IDENTICAL_ACCOUNT; - } - if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && - context->direction == DM_AUTH_SOURCE && subject == SUBJECT_PRIMARY) { - return DM_SHARE; - } - if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && - context->direction == DM_AUTH_SINK && subject == SUBJECT_SECONDARY) { - return DM_SHARE; - } - if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { - return DM_POINT_TO_POINT; - } - if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_USER && appList.empty()) { - return DM_LNN; - } - return DM_INVALIED_BINDTYPE; -} - -bool AuthSinkNegotiateStateMachine::HaveSameTokenId(std::shared_ptr context, - const std::vector &tokenList) -{ - // Store the token of src and sink. The size must be 2. - if (tokenList.size() != 2) { - LOGE("HaveSameTokenId invalid tokenList size."); - return false; - } - - // tokenIdList = [srcTokenId, sinkTokenId] - std::string srcTokenIdHash = Crypto::Sha256(tokenList[0]); - std::string sinkTokenIdHash = Crypto::Sha256(tokenList[1]); - - return (srcTokenIdHash == context->accesser.tokenIdHash) && - (sinkTokenIdHash == context->accessee.tokenIdHash); -} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index b8006dd2b..162c7baea 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -292,5 +292,61 @@ int32_t DmAuthState::GetAclBindType(std::shared_ptr context, std: } return DM_UNKNOWN_TYPE; } + +uint32_t DmAuthState::GetCredType(std::shared_ptr context, const JsonItemObject &credInfo) +{ + int32_t credType = credInfo[FILED_CRED_TYPE].Get(); + int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); + int32_t subject = credInfo[FILED_SUBJECT].Get(); + std::vector appList; + credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); + if (credType == ACCOUNT_RELATED && authorizedScope == SCOPE_USER) { + return DM_IDENTICAL_ACCOUNT; + } + if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && + context->direction == DM_AUTH_SOURCE && subject == SUBJECT_PRIMARY) { + return DM_SHARE; + } + if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && + context->direction == DM_AUTH_SINK && subject == SUBJECT_SECONDARY) { + return DM_SHARE; + } + if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { + return DM_POINT_TO_POINT; + } + if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_USER && appList.empty()) { + return DM_LNN; + } + return DM_INVALIED_BINDTYPE; +} + +uint32_t DmAuthState::GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo) +{ + CHECK_NULL_RETURN(context, DM_INVALIED_BINDTYPE); + if (!credInfo.Contains(FILED_CRED_TYPE) || !credInfo[FILED_CRED_TYPE].IsNumberInteger() || + !credInfo.Contains(FILED_AUTHORIZED_SCOPE) || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumberInteger() || + !credInfo.Contains(FILED_SUBJECT) || !credInfo[FILED_SUBJECT].IsNumberInteger()) { + LOGE("credType or authorizedScope invalid."); + return DM_INVALIED_BINDTYPE; + } + return GetCredType(context, credInfo); +} + +bool DmAuthState::HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList) +{ + // Store the token of src and sink. The size must be 2. + if (tokenList.size() != 2) { + LOGE("HaveSameTokenId invalid tokenList size."); + return false; + } + + // tokenIdList = [srcTokenId, sinkTokenId] + std::string srcTokenIdHash = Crypto::Sha256(tokenList[0]); + std::string sinkTokenIdHash = Crypto::Sha256(tokenList[1]); + + return (srcTokenIdHash == context->accesser.tokenIdHash) && + (sinkTokenIdHash == context->accessee.tokenIdHash); +} + } // namespace DistributedHardware } // namespace OHOS -- Gitee From 457e46d78fcb7fcec848005227084f953322e65f Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sun, 6 Apr 2025 18:10:49 +0800 Subject: [PATCH 8/8] add jsonobject sdk Signed-off-by: hwzhangchuang --- bundle.json | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/bundle.json b/bundle.json index aabf1cb47..2f4868a16 100644 --- a/bundle.json +++ b/bundle.json @@ -99,8 +99,17 @@ ], "header_base": "//foundation/distributedhardware/device_manager/interfaces/mini_tools_kits/native_cpp/include" } - },{ + }, { "name": "//foundation/distributedhardware/device_manager/interfaces/cj/kits:cj_distributed_device_manager_ffi" + }, { + "type": "so", + "name": "//foundation/distributedhardware/device_manager/json:devicemanagerjson", + "header": { + "header_files": [ + "json_object.h" + ], + "header_base": "//foundation/distributedhardware/device_manager/json/include" + } }], "test": [ "//foundation/distributedhardware/device_manager:device_manager_test" -- Gitee